2014-09-11 77 views
10

我有以下plunker:AngularJS - 为什么我的指令隔离范围变量未定义?

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

当我运行此,templateUrl的范围是不确定的。为什么?

这里我的假设是,它试图在父范围中找到一个名为template.html的变量,但不能,因此它将它分配给未定义的变量。如果是这样,我如何将它作为字符串而不是范围变量传入?

HTML:

<body ng-app="myApp"> 
    <div ng-controller="TestCtrl"> 
     <test-directive ng-model="testModel" 
         template-url="template.html"> 
     </test-directive> 
    </div> 
</body> 

的.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 
     } 
    } 
}); 

回答

11

只需更改范围:

scope: { 
     templateUrl: "@" 
    }, 

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

关键是'='和'@'的区别。你可以参考https://docs.angularjs.org/guide/directive

+0

指令API已被移至$ compile。[https://docs.angularjs.org/api/ng/service/$compile] – 2016-03-02 13:00:00

+1

解答详细差异的优秀答案: http://stackoverflow.com/a/14063373/3123195 – 2016-05-03 13:03:01

3

我想通了,我的问题。我需要使用@而不是=。

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); // <-- Works perfectly 
     } 
    } 
}); 
3

当你将等号(=)变为指令时,你必须在$ scope下定义这个属性,否则它不起作用,它会产生错误''。请参阅角度文档link。是否可以尝试templateUrl:“=?”或在$范围下。

根据角文档

<!-- ERROR because `1+2=localValue` is an invalid statement --> 
<my-directive bind="1+2"> 

<!-- ERROR because `myFn()=localValue` is an invalid statement --> 
<my-directive bind="myFn()"> 

<!-- ERROR because attribute bind wasn't provided --> 
<my-directive> 

要解决此错误,总是使用与被作用域属性路径表达式双向数据绑定:

<my-directive bind="some.property"> 
<my-directive bind="some[3]['property']"> 

您的解决方案是在这里plnkr