简体   繁体   中英

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.

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. :)

try this :

<div ng-include="'content/{{topic}}.html'"></div>

In angularjs , scope variable are access in HTML using The double curly brace notation {{ }} .

Try as follows:

<ng-include src="topic"> </ng-include>

Make sure you have define $scope.topic = "whateveryouwant" ;

-----------OR-----------

You could do it like:

<ng-include src="getTopic()"></ng-include>

Controller:

function AppCtrl ($scope) {
  $scope.getTopic= function () {
      return 'partials/whatever.html';
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM