AngularJS - Custom Filter for ManyToMany Relationship
Custom Filter for options that are a ManyToMany Relationship, Note the Filter runs Twice a sideaffect of Angulars 'Dirty Data Checking'
by sjmcpherson
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"></script>
<div ng-controller="MyCtrl">
<label ng-repeat="colour in colours | unique:'name'">
<input type="checkbox" ng-init="activeColors[colour.name]=true" ng-model="activeColors[colour.name]" />{{colour.name}}
</label>
<h3>Full List:</h3>
<div ng-repeat="colour in colours">{{colour}}</div>
<h3>Active List:</h3>
<div ng-repeat="colour in colours | manyToMany:'name':activeColors">{{colour.name}}</div>
<h3>Active Colors:</h3>
{{activeColors}}
</div>
JavaScript
var myApp = angular.module('myApp', ['ui.directives','ui.filters']);
myApp.controller('MyCtrl',function($scope) {
$scope.activeColors = {};
$scope.colours = [
{id:'1', name: 'red'},
{id:'2', name: 'blue'},
{id:'3', name: 'green'},
{id:'4', name: 'red'}
];
})
.filter('manyToMany',function(){
return function(arrInput,strProperty,objMany){
console.log(arrInput);
console.log("strProperty "+strProperty);
console.log(objMany);
var arrFiltered = [];
for(var i=0,max=arrInput.length;i<max;i++){
if(objMany[arrInput[i][strProperty]] === true){
arrFiltered.push(arrInput[i]);
}
};
return arrFiltered;
}
});