将JS变量添加到AngularJS目录中?

时间:2016-05-15 12:15:34

标签: javascript angularjs directory angularjs-ng-include

我似乎无法使用以下代码:

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

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

我推断出变量是问题,因为以下代码可以正常工作:

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

有人知道我该怎么做吗?

更新

按照Steffen的链接,我写了以下代码,但仍然没有运气:

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

感谢。

3 个答案:

答案 0 :(得分:1)

基于Steffen的jsfiddle,以下是我将JavaScript变量传递给AngularJS并将其用于定义目录的方法:

<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! -->

非常感谢所有人的回答。 :)

答案 1 :(得分:0)

试试这个:

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

angularjs 中,使用 variable are access 在HTML中查看范围double curly brace notation {{ }}

答案 2 :(得分:0)

尝试如下:

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

确保您已定义$scope.topic = "whateveryouwant";

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

你可以这样做:

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

控制器:

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