AngularJS - creating a filtered search from a set of filter objects

I am trying to create an object for a filtered search. The user can add multiple filters to the search and can add the same filter more than once with a different value.

The user is offered a button to add filters. Each one added shows a selection populated from the list of available filters.

At the moment, when I add two identical filters (ie two "Filter A"), they both have the same basic value. How can I use Angular to break a link from a source filter array when a filter is selected in the selection box?

JSFiddle Here

HTML

<div ng-app="myApp"> <div ng-controller="MyCtrl"> <button data-ng-click="addFilter()">Add Filter</button> <div data-ng-repeat="c in current.filters"> <div class="select-box"> <select data-ng-model="c.filter" data-ng-options="filter.name for filter in filters"></select> <input type="text" placeholder="Filter value" data-ng-model="c.filter.value"> </div> </div> <pre>{{current | json}}</pre> </div> 

Javascript

 var app = angular.module('myApp', []); app.controller('MyCtrl', function($scope) { $scope.current = {"filters":[]}; $scope.filters = [ {"id":"1", "name":"Filter A", "value":""}, {"id":"2", "name":"Filter B", "value":""}, {"id":"3", "name":"Filter C", "value":""}, {"id":"4", "name":"Filter D", "value":""} ]; $scope.addFilter = function() { $scope.current.filters.push({}); }; }); 
+4
source share
1 answer

I think AngularJS does not handle select ng-model directives as you expect. In this case, it is bound to the selected filter object from the filter array. Therefore, when you change the value of a filter with the same name, all filters with this name see the change, because the underlying object is the same.

What you need to do is bind the filter value yourself, and not as part of the filter object.

Change this line

 <input type="text" placeholder="Filter value" data-ng-model="c.filter.value"> 

to

 <input type="text" placeholder="Filter value" data-ng-model="c.value"> 

You also do not need to define a β€œvalue” field for each filter.

Updated code: http://jsfiddle.net/HyRUV/5/

+1
source

Source: https://habr.com/ru/post/1491595/


All Articles