[英]Remove duplicates from array directive
I have a div which shoes the names. 我有一个穿上名字的div。 I want to remove the duplicates in my array.
我想删除阵列中的重复项。 I have done this with
filter
, but i want to know how we can extend this to build a directive
. 我已经使用
filter
做到了这一点,但是我想知道我们如何扩展它来构建directive
。
<div ng-controller="MainController">
<ul>
<li ng-repeat="name in names | unique">
{{name}}
</li>
</ul>
</div>
Below is the filter code. 以下是过滤器代码。
angular.module('app')
.controller('MainController', ['$scope', function($scope){
$scope.names = ['a','b','c','d','a','c'];
}])
.filter('unique', function(){
return function(names){
var obj = {};
names.forEach(function(name){
obj[name] = null;
})
return Object.keys(obj);
}
})
.directive('unique', function(){
return {
link: function(scope, elem, attr){
}
}
})
How can i build a directive
which removes duplicates from my array. 我如何建立一个
directive
,从我的数组中删除重复项。
Here's how I would write it: 这是我的写法:
angular.module('app')
.controller('MainController', ['$scope', function($scope){
$scope.names = ['a','b','c','d','a','c'];
}])
.directive('uniqueArray', function(){
return {
restrict: 'E',
scope: {
arr: '='
}
template: '<ul><li ng-repeat="item in unique_arr">{{item}}</li></ul>',
controller: function($scope){
function get_unique(items){
var obj = {};
angular.forEach(items, function(item){
obj[item] = null;
});
return Object.keys(obj);
}
$scope.unique_arr = get_unique($scope.arr);
}
}
})
and in the HTML: 并在HTML中:
<unique-array arr="names"></unique-array>
I think a directive is unnecessary as though as it's basically acting as a wrapper 我认为指令是不必要的,因为它基本上起包装器的作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.