是否可以有一个带有转发器的指令?
我想要的是按字母顺序创建一个人员列表,其中针对每组字母过滤人员列表。
该指令如下:
.directive('azList', ['$compile', function($compile){
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.split('');
var group = '';
letters.forEach(function(letter){
group = group + '\
<div class="list__group" id="list_' + letter + '">\
<h4 class="list__header">' + letter + '</h4>\
<ul class="list__items">\
<li ng-repeat="person in people | orderBy: [{{person.lastname}}, {{person.firstname}}] | firstLetter:{{person.lastname}}:' + letter + '">\
<a ui-sref="people.details({ personId: {{person.id}} })">\
<span class="list__icon"><img src="img/avatar.png"></span>\
<span class="list__text">\
<span class="list__text__name">{{person.firstname}} <b>{{person.lastname}}</b></span>\
</span>\
</a>\
</li>\
</ul>\
</div>';
});
return {
restrict: 'AECM',
template: group
};
}])
然后是过滤器:
.filter('firstLetter', function () {
return function (input, key, letter) {
input = input || [];
var out = [];
input.forEach(function (item) {
if(letter == '#') {
if ( !isNaN(parseInt(item[key][0])) )
out.push(item);
}
else if (item[key][0].toLowerCase() == letter.toLowerCase()) {
out.push(item);
}
});
return out;
}
});
然后我这样使用它:
<az-list></az-list>
但是我只是得到了字母列表,它并没有调用中继器......
最佳答案
指令应该有返回对象,该对象将是指令定义对象。我不确定您在指令中做了什么。
.directive('azList', ['$compile', function($compile){
return {
restrict: 'AECM',
template: '<div>myTempolate</div>'
}
})];
此外,您在对 ng-repeat
应用过滤器时确实在一些地方使用了 {{}}
,您应该将其更改为下面的内容。
<div class="list__group" id="list_' + letter + '">\
<h4 class="list__header">' + letter + '</h4>\
<ul class="list__items">\
<li ng-repeat="person in people | orderBy: [person.lastname, person.firstname] | firstLetter:person.lastname:' + letter + '">\
<a ui-sref="people.details({ personId: person.id })">\
<span class="list__icon"><img src="img/avatar.png"></span>\
<span class="list__text">\
<span class="list__text__name">{{person.firstname}} <b>{{person.lastname}}</b></span>\
</span>\
</a>\
</li>\
</ul>\
</div>';
查看演示 plunkr here
<小时/>理想情况下,您应该在模板上使用 ng-repeat
来多次重复该模板。仅用于生成模板的指令是没有意义的,因为 ng-repeat
已经存在了。
ng-repeat
版本
<div ng-repeat="letter in letters" class="list__group" id="list_{{letter}}">
<h4 class="list__header">{{letter}}</h4>
<ul class="list__items">
<li ng-repeat="person in people | orderBy: [person.lastname, person.firstname] | firstLetter:person.lastname:letter">
<a ui-sref="people.details({ personId: person.id })">
<span class="list__icon"><img src="img/avatar.png"></span>
<span class="list__text">
<span class="list__text__name">
{{person.firstname}}
<b>{{person.lastname}}</b></span>
</span>
</a>
</li>
</ul>
</div>
关于javascript - 带转发器的 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36749260/