在ng-include中使用变量作为表达式

时间:2016-04-26 17:17:00

标签: javascript html angularjs directive

此代码有效:

<div ng-include src="'Test.html'"></div>

此代码不是:

<div ng-include src="ctrl.URL"></div>

ctrl.URL设置为"Test.html")。我还将其设置为'Test.html'"'Test.html'",结果相同。

如何成功将其转换为在ng-include src中使用的表达式?我想我缺少一些关于如何解析字符串的知识,但我非常确定'Test.html'应该有效。

2 个答案:

答案 0 :(得分:1)

我发现我无法重命名自己的变量。 ctrl.URL真的是ctrl.URl。现在一切正常。

答案 1 :(得分:0)

检查一下,也许这个fiddle会对你有帮助。

HTML和模板:

 <div ng-controller="Ctrl">
    <select ng-model="template" ng-options="t.name for t in templates">
     <option value="">(blank)</option>
    </select>
    url of the template: <tt>{{template.url}}</tt>
    <hr/>
    <div ng-include src="template.url" onload='myFunction()'></div>
  </div>

<!-- template1.html -->
<script type="text/ng-template" id="template1.html">
  Content of template1.html
</script>

<!-- template2.html -->
<script type="text/ng-template" id="template2.html">
    <p ng-class="color">Content of template2.html</p>
</script>

控制器:

function Ctrl($scope) {
    $scope.templates = [{
        name: 'template1.html',
        url: 'template1.html'},
    {
        name: 'template2.html',
        url: 'template2.html'}];
    $scope.template = $scope.templates[0];

    $scope.myFunction = function() {
        $scope.color = 'red';
    }
}