AngularJS 具有隔离作用域、ng-repeat 和 controllerAs 的指令
AngularJS directive with isolate scope, ng-repeat, and controllerAs
function directive() {
return {
restrict: 'E',
template: '<button ng-repeat="x in j.array" ng-click="j.set(x)">{{x}}</button>',
replace: true,
//scope: {},
bindToController: {
array: '=',
answer: '='
},
controller: function() {
var j = this;
j.set = function(data) {
j.answer = data;
};
},
controllerAs: 'j'
};
}
当我取消注释范围并创建隔离范围时,该指令不再有效。我正在尝试确定原因。
通常我仍然可以访问 ng-repeat
中的 controllerAs,在这个例子中,当我丢失它时它仍然可以在 $parent.j
中使用。我认为有3种解决方案。
解决方案 1 是让它不在隔离范围内。
解决方案 2 是将重复中对 j
的每个引用转换为 $parent.j
.
解决方案 3 是有一些方法可以使用 j
而不必使用我不知道的 $parent
。
可能与replace: true
有关。如果将 button
包裹在 div
中,它似乎可以工作!我做了一个小 Plunker here 来演示。
function directive() {
return {
restrict: 'E',
template: '<button ng-repeat="x in j.array" ng-click="j.set(x)">{{x}}</button>',
replace: true,
//scope: {},
bindToController: {
array: '=',
answer: '='
},
controller: function() {
var j = this;
j.set = function(data) {
j.answer = data;
};
},
controllerAs: 'j'
};
}
当我取消注释范围并创建隔离范围时,该指令不再有效。我正在尝试确定原因。
通常我仍然可以访问 ng-repeat
中的 controllerAs,在这个例子中,当我丢失它时它仍然可以在 $parent.j
中使用。我认为有3种解决方案。
解决方案 1 是让它不在隔离范围内。
解决方案 2 是将重复中对 j
的每个引用转换为 $parent.j
.
解决方案 3 是有一些方法可以使用 j
而不必使用我不知道的 $parent
。
可能与replace: true
有关。如果将 button
包裹在 div
中,它似乎可以工作!我做了一个小 Plunker here 来演示。