0

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.

2 Answers 2

3

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)
});
Sign up to request clarification or add additional context in comments.

1 Comment

Why are you returning element from predicate? It will filter out falsy elements as well.
1

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>

2 Comments

hi.. thanks for the help. Nevertheless it is not working, i am having a blank page with the angular version.. no errors..
You didn't correctly bootstrapped angular, see this one: plnkr.co/edit/6EaRknVsvaHdFf7u6URh?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.