将 JS 变量添加到 AngularJS 目录?

Adding a JS Variable to a AngularJS Directory?

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

<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 的 link,我写了下面的代码,但仍然没有运气:

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

谢谢。

试试这个:

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

In angularjs ,范围 variable are access in HTML 使用 double curly brace notation {{ }}

尝试如下:

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

确保你已经定义了$scope.topic = "whateveryouwant"

------------或------------

你可以这样做:

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

控制器:

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

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

非常感谢大家的回答。 :)