Povertyman
Povertyman

Reputation: 1

Using angular js filter to remove a value from a list

i am new to angular js. Having some troubles solving this problem.

suppose i have this :

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
   $scope.num = ["1", "2", "3","toto","5","6","toto","7"];

});

how do i make an iteration so that all the 'toto' are removed from the list and it returns the array without the 'toto'. I have tried using filter but it is not working. how can i do this by using filter? Thanks

A little help please.

Upvotes: 0

Views: 2118

Answers (2)

sumair
sumair

Reputation: 386

Use it like

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) { 

  $scope.num = ["1", "2", "3","toto","5","6","toto","7"];

  $scope.num = $scope.num.filter(function(n){
         return (n != "toto")
   });
  console.log($scope.num)
});

Upvotes: 3

cfz42
cfz42

Reputation: 384

Not sure if you want to use the javascript filter function or angular filters.

@sumair showed you the javascript one, here is the angular one using $filter :

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $filter) {
    $scope.num = ["1", "2", "3", "toto", "5", "6", "toto", "7"];

    $scope.num = $filter('filter')($scope.num, function(item) {
        return item !== 'toto';
    });
});

You might want to isolate the function passed to $filter so that you can use it directly from the html to alter the view without touching the model :

js:

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) { 

  $scope.num = ["1", "2", "3","toto","5","6","toto","7"];

  $scope.filterCriteria = function(item) {
      return item != 'toto';
  };
});

html:

<ul>
    <li ng-repeat="item in num | filter:filterCriteria" ng-bind="item"></li>
</ul>

Upvotes: 1

Related Questions