Angularjs 在指令中绑定数组元素 ng-repeat
Angularjs binding array element ng-repeat in directive
我正在尝试使用 ng-repeat 和指令显示数组的元素。指令部分对解决方案很重要。但是,数组的元素未被绑定并显示空值。
可以在 http://jsfiddle.net/qrdk9sp5/
找到 fiddle
HTML
<div ng-app="app" ng-controller="testCtrl">
{{chat.words}}
<test ng-repeat="word in chat.words"></test>
</div>
JS
var app = angular.module('app', []);
app.controller("testCtrl", function($scope) {
$scope.chat = {
words: [
'Anencephalous', 'Borborygm', 'Collywobbles'
]
};
});
app.directive('test', function() {
return {
restrict: 'EA',
scope: {
word: '='
},
template: "<li>{{word}}</li>",
replace: true,
link: function(scope, elm, attrs) {}
}
});
输出
["Anencephalous","Borborygm","Collywobbles"]
•
•
•
预期输出
["Anencephalous","Borborygm","Collywobbles"]
•Anencephalous
•Borborygm
•Collywobbles
感谢您的帮助
您没有绑定 word
。
您使用了隔离作用域。如果你不绑定它的 scope
属性,它将无法工作。
scope: {
word: '='
},
这样试试
<test word="word" ng-repeat="word in chat.words"></test>
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.chat= {words: [
'Anencephalous', 'Borborygm', 'Collywobbles'
]};
});
app.directive('test', function() {
return {
restrict: 'EA',
scope: {
word: '='
},
priority: 1001,
template: "<li>{{word}}</li>",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
您的指令需要 运行 在 ng-repeat 之前使用更高的优先级,因此当 ng-repeat 克隆元素时它能够选择您的修改。
来自 Directives user guide have an explanation on how ng-repeat works 的 "Reasons behind the compile/link separation" 部分。
当前 ng-repeat 优先级为 1000,因此高于此优先级的都应该执行。
我正在尝试使用 ng-repeat 和指令显示数组的元素。指令部分对解决方案很重要。但是,数组的元素未被绑定并显示空值。
可以在 http://jsfiddle.net/qrdk9sp5/
找到 fiddleHTML
<div ng-app="app" ng-controller="testCtrl">
{{chat.words}}
<test ng-repeat="word in chat.words"></test>
</div>
JS
var app = angular.module('app', []);
app.controller("testCtrl", function($scope) {
$scope.chat = {
words: [
'Anencephalous', 'Borborygm', 'Collywobbles'
]
};
});
app.directive('test', function() {
return {
restrict: 'EA',
scope: {
word: '='
},
template: "<li>{{word}}</li>",
replace: true,
link: function(scope, elm, attrs) {}
}
});
输出
["Anencephalous","Borborygm","Collywobbles"]
•
•
•
预期输出
["Anencephalous","Borborygm","Collywobbles"]
•Anencephalous
•Borborygm
•Collywobbles
感谢您的帮助
您没有绑定 word
。
您使用了隔离作用域。如果你不绑定它的 scope
属性,它将无法工作。
scope: {
word: '='
},
这样试试
<test word="word" ng-repeat="word in chat.words"></test>
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.chat= {words: [
'Anencephalous', 'Borborygm', 'Collywobbles'
]};
});
app.directive('test', function() {
return {
restrict: 'EA',
scope: {
word: '='
},
priority: 1001,
template: "<li>{{word}}</li>",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
您的指令需要 运行 在 ng-repeat 之前使用更高的优先级,因此当 ng-repeat 克隆元素时它能够选择您的修改。
来自 Directives user guide have an explanation on how ng-repeat works 的 "Reasons behind the compile/link separation" 部分。
当前 ng-repeat 优先级为 1000,因此高于此优先级的都应该执行。