Reputation: 4353
I'm implementing a filter using chips of Angular Material. When user clicks on chips, the value associated to that chip should be stored in the array. The same way, when user deselects the chip, that value should pop from the array.
I was able to store the values but selecting and deselecting are causing addition of duplicate values in the array and I'm not able to pop them out when user deselects the chip.
Here's the excerpt from my code.
HTML Code
<div layout="row">
<md-chips ng-repeat="filter in filters" readOnly="true">
<md-chip ng-style="{'background': filter.isActive ? 'green' : '' }" class="chipStyling" ng-click="setActiveFilter(filter,$index)">
{{filter.name}}
</md-chip>
</md-chips>
</div>
JS Code
angular.module('BlankApp', ['ngMaterial', 'ngMessages'])
.controller('ctrl', function($scope) {
$scope.selectedFilters = []
$scope.isActive = false;
$scope.filters = [{
name: 'Google',
code: 'g',
isActive: false
},
{
name: 'Facebook',
code: 'f',
isActive: false
},
{
name: 'Twitter',
code: 't',
isActive: false
}
]
$scope.setActiveFilter = function(filter, index) {
filter.isActive = !filter.isActive;
if (filter.isActive) {
$scope.selectedFilters.push(filter.code);
console.log('selected filter - ' + $scope.selectedFilters)
}
}
});
I created a Code Pen on this issue. Could anyone please review and correct me what I was doing wrong.
Upvotes: 0
Views: 181
Reputation: 1063
Use a splice
method for remove element from array
$scope.setActiveFilter = function(filter, index) {
filter.isActive = !filter.isActive;
if (filter.isActive) {
$scope.selectedFilters.push(filter.code);
console.log('selected filter - ' + $scope.selectedFilters)
} else {
let index = $scope.selectedFilters.indexOf(filter.code);
if (index > -1) {
$scope.selectedFilters.splice(index, 1);
}
}
}
Upvotes: 1