关于 AngularJS 指令,我遇到了从另一个指令中调用指令的情况,我有以下问题。
- 为什么我不能在我的链接函数中引用 scope.bindValue?有没有办法可以从 scope.bindValue 计算一个值并将其设置为范围?
- 为什么子指令可以在 scope:{} 中使用“@”绑定,但在链接函数中不能使用 scope.value = attrs.value?
以下所有内容都可以在http://jsfiddle.net/sdg9/AjDtt/13/上看到
HTML:
<directive bind-value="12" value="7"></directive>
JS:
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