0
我有下面的腳本如何同指令多次與父母使用AngularJS
// Code goes here
angular.module('default', [])
.directive('webAbc', function($log) {
return {
restrict: 'A',
controller: function($scope, $element, $attrs, $transclude) {
this.checkboxes = [];
this.updateLinkedCheckboxes = function(value) {
angular.forEach(this.checkboxes, function(checkbox, index) {
checkbox.setChecked(value);
});
};
}
};
})
.directive('webDef', function($log) {
return {
restrict: 'C',
require: '^webAbc',
link: function (scope, iElement, iAttrs, webAbc, transcludeFn) {
iElement.bind('change', function() {
webAbc.updateLinkedCheckboxes(iElement.prop('checked'));
scope.$apply();
});
}
};
})
.directive('webGhi', function($log) {
return {
restict: 'A',
require: '^webAbc',
link: function (scope, iElement, iAttrs, webAbc, transcludeFn) {
scope.setChecked = function(value) {
$log.log('This element ' + iAttrs.name + ' cheked: ' + (!value ? 'checked' : ''));
$log.log(value);
if (value)
{
iElement.attr('checked', 'checked');
}
else
{
iElement.remoteAttr('checked');
}
};
webAbc.checkboxes.push(scope);
}
};
});
應該選擇或不選擇在顯着列表中的所有複選框,但我不能使它與下面的工作解。
首先看起來,只有最後一個webGhi
由於在控制檯中打印而可見。甚至更多,看來,我不能因某種原因取消選中複選框。
鏈接到一個例子:http://jsbin.com/difihabe/1/
謝謝。
這是偉大的。謝謝。爲了清楚起見,如果沒有定義局部作用域,那麼最後一個元素將覆蓋它,因此只有它被使用,是正確的?而設置本地範圍將使每個行都是唯一的,正確的? – Eugene
指令的所有四個實例將使用相同的作用域(父級)。 'webAbc.checkboxes.push(scope);'將被調用四次,這意味着在數組中會有四個對父作用域的引用。所有四個實例將在同一範圍內定義'scope.setChecked = function(value)'。這意味着數組中的所有四個引用將具有由四個中最後一個定義的'setChecked',因爲它將覆蓋其他四個引用。由於'setChecked'函數包含了指令第四個實例的'iElement'的引用,所以在您的示例中,這是一個正在工作的(半工作)。 – tasseKATT