我正在尝试使用 ng-repeat 和指令显示数组的元素。指令部分对解决方案很重要。但是,数组的元素未绑定并显示空值。
小提琴可以在 http://jsfiddle.net/qrdk9sp5/
.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>
DEMO
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 克隆元素时,它能够选择您的修改。
指令用户指南中的"编译/链接分离背后的原因"部分解释了ng-repeat的工作原理。
当前的ng-repeat优先级是1000,所以任何高于此值的优先级都应该这样做。