Search code examples
javascriptangularjsdirectoryangularjs-ng-include

Adding a JS Variable to a AngularJS Directory?


I can't seem to get the following code to work:

<script>alert(topic);</script> <!-- Outputs: "dynamics" -->

<div ng-include="'content/' + topic + '.html'"></div> <!-- Does not work. -->

I have deduced the variable is the problem as the following code does work:

<div ng-include="'content/' + 'dynamics' + '.html'"></div> <!-- Works. -->

Does anybody know how I can do this?

Update:

Following Steffen's link, I have written the following code, but still no luck:

<script>
    alert(topic); // Outputs "dynamics"

    var app = angular.module('myapp', []);

    app.controller('MainCtrl', ['$scope', '$window', function ($scope, $window) {
        $scope.topic = $window.topic;
    }]);
</script>

<div ng-app="myapp" ng-controller="MainCtrl" ng-include="'content/' + 
    topic + '.html'"></div>  <!-- Does not work. -->

Thanks.


Solution

  • Based on Steffen's jsfiddle, here is how I passed a JavaScript variable to AngularJS and used it in defining a directory:

    <script>
        // Create module.
        var app = angular.module('app', []);
    
        // Add controller to module.
        app.controller('MainCtrl', ['$scope', '$window', function ($scope, $window) {
            $scope.topic = $window.topic;
            console.log($scope.topic);
        }]);
    </script>
    
    <div ng-app="app" ng-controller="MainCtrl" ng-include="'content/' + 
        topic + '.html'"></div> <!-- Works! -->
    

    Many thanks to all for their answers. :)