关于AngularJS指令,我遇到了从另一个指令中调用指令的情况,我有以下问题。
以下所有内容都可以在http://jsfiddle.net/sdg9/AjDtt/13/上看到
HTML:
<directive bind-value="12" value="7"></directive>联署材料:
var myApp = angular.module('myApp', []);
var commonTemplate = '<div>{{name}} bind-value is: {{bindValue}} </div><div>{{name}} value is: {{value}} </div><div>{{name}} add one to bind-value is: {{addOneBindValue}} </div><div>{{name}} add one to value is: {{addOneValue}} </div><br/>';
myApp.directive('directive', function () {
return {
scope: {
bindValue: "@",
},
template: commonTemplate + '<br/><sub-directive bind-value="{{value}}" value="{{value}}"></sub-directive>',
restrict: 'E',
link: function (scope, element, attrs) {
scope.name = "Directive";
scope.value = attrs.value;
scope.addOneBindValue = parseInt(scope.bindValue) + 1;
scope.addOneValue = parseInt(scope.value) + 1;
}
};
});
myApp.directive('subDirective', function () {
return {
scope: {
bindValue: "@"
},
template: commonTemplate,
restrict: 'E',
link: function (scope, element, attrs) {
scope.name = "SubDirective";
scope.value = attrs.value;
scope.addOneBindValue = parseInt(scope.bindValue) + 1;
scope.addOneValue = parseInt(scope.value) + 1;
}
};
});输出:
Directive bind-value is: 12
Directive value is: 7
Directive add one to bind-value is: null <--- why?
Directive add one to value is: 8
SubDirective bind-value is: 7
SubDirective value is: <--- why?
SubDirective add one to bind-value is: null
SubDirective add one to value is: null 发布于 2013-03-15 17:54:35
在运行链接函数时,内插属性(即使用{{}}的属性)和使用“@”定义的范围属性不可用。您需要使用attrs.$observe() (或scope.$watch( @ property here, ...))来获得值(异步)。
因此,当您尝试使用scope.bindValue时,它是不可用的。
类似地,在您的subDirective中,属性value具有{{}},因此当您试图使用它时,它的值也将不可用。您还需要为此定义一个“@”指令属性。
工作小提琴。
异步要求的原因是{{}}中的项可能会发生变化,您通常希望您的指令注意到(然后做一些事情--比如更新"addOne“值)。当属性值包含{{}}时,“@”通常与隔离作用域一起使用。
如果属性值是常量,并且不使用模板(或templateUrl)中的值,那么“@”可能不应该使用。在链接函数中,如果值是字符串,只需使用attrs.attrName,如果属性是数字,则使用scope.$eval(attrs.attrName) (如果您知道它是数字,则使用parseInt(attrs.attrName) )。
https://stackoverflow.com/questions/15438837
复制相似问题