AngularJS - 为什么我的指令隔离范围变量未定义?

Sco*_*tie 11 angularjs angularjs-directive angularjs-scope

我有以下的plunker:

http://plnkr.co/edit/7YUpQ1tEjnUaX01txFcK?p=preview

当我运行它时,在范围中未定义templateUrl.为什么?

我在这里的假设是,它试图在父作用域中找到名为template.html的变量,但不能,因此它将它分配给undefined.如果是这样,我如何将其作为字符串而不是范围变量传递?

HTML:

<body ng-app="myApp">  
   <div ng-controller="TestCtrl">
      <test-directive ng-model="testModel" 
                      template-url="template.html">
      </test-directive>
   </div>
</body>
Run Code Online (Sandbox Code Playgroud)

.js文件

var app = angular.module("myApp", []);

app.controller("TestCtrl", function($scope) {
  $scope.testModel = {}
});

app.directive("testDirective", function () {
    return {
        restrict: 'E',
        scope: {
            model: "=ngModel",
            templateUrl: "="
        },
        template: "<div ng-include='templateUrl'></div>",
        link: function (scope, element, attrs) {
           console.log(scope.templateUrl);  // <-- Shows as undefined
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

cre*_*per 13

只需更改范围:

    scope: {
        templateUrl: "@"
    },
Run Code Online (Sandbox Code Playgroud)

你会得到输出'template.html'.

关键点是'='和'@'之间的区别.您可以参考https://docs.angularjs.org/guide/directive.

  • 解释细节差异的优秀答案:http://stackoverflow.com/a/14063373/3123195 (2认同)