我正在尝试创建一个指令,我需要一些额外的细节,这些细节必须作为元素的属性传递。
这些值是静态的。即:父作用域中不会有任何作用域引用(它是一个 bool 值)
在指令链接函数中,我需要这些属性可以在指令的链接函数中访问,但值未定义。
标记:
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<div my-directive local-attr="attribute" local-ref="ref">
</div>
</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function(){
return {
scope: {
localAttr:'@',
localRef:'='
},
link: function(scope, iElement, iAttrs, controller) {
console.log(scope.localAttr, scope.localRef);
}
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
$scope.ref="reg"
}]);
在此演示中,我需要在链接函数中为 scope.localAttr
获取值 attribute
。
演示:Fiddle
最佳答案
如果值是 100% 静态的,您可以使用 iAttrs.localAttr
(并且您可以跳过 scope: {..}
中的绑定(bind))
如果值应该被插值(有 {{...}}
)你应该使用 iAttrs.$observe('localAttr', cb)
(还有您可以跳过在 scope: {...}
)
如果您想对其他作用域属性进行一些操作,您应该$scope.watch('localAttr', cb)
。
甚至可以预料,在链接范围期间可能没有完全构建。在关于链接函数的“作用域”参数的 AngularJS 文档中有
The scope to be used by the directive for registering watches.
http://docs.angularjs.org/guide/directive
所以一般只能注册观察者,不能获取值。
关于javascript - 为什么这个作用域属性在链接函数中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14953488/