juanObrach
juanObrach

Reputation: 158

filter an array with objects with Angular.js

Heading

Hello, I have this $scope array with objects in my Angular.js controller:

$scope.recipes = [
 {
 name :"Ceasar Salad",
 ingredients:["chicken","lettuce"],
 time:"8'"
 },
 {
 name :"Lupus Salad",
 ingredients:["lupus","lettuce"],
 time:"18'"
 }

]

Then I repeat ech object in $scope.recipe

ul(ng-repeat="r in recipes | filter:ingredient")
 li
  h3{{r.name}}
  i(class="fa fa-clock-o")
  span{{r.time}}
  i(ng-class="heart" ng-click="change()")

And use this input with ng-model to filter in my ng-repeat

input(type="text" ng-model="ingredient")

The question is. How can I filter only words that are in each "ingredients" property of each object.

thanks.

Upvotes: 1

Views: 3349

Answers (3)

Majid Yaghouti
Majid Yaghouti

Reputation: 913

This way of filtering slows down your running speed. A better filtering is like:

In controller:

$scope.recipes = [
        {
            name: "Ceasar Salad",
            ingredients: ["chicken", "lettuce"],
            time: "8'"
        },
        {
            name: "Lupus Salad",
            ingredients: ["lupus", "lettuce"],
            time: "18'"
        }
    ];

$scope.ingredient = "";

$scope.filterByIngredient = function () {
    $scope.filteredRecipes = $scope.ingredient.length ? $filter('filter')($scope.recipes, function (r) {
        return r.ingredients.indexOf($scope.ingredient) > -1;
    }) : $scope.recipes;
};

$scope.filterByIngredient();

In view:

<ul ng-repeat="r in filteredRecipes">
    <li>
        <h3>{{r.name}}</h3>
        <i class="fa fa-clock-o"></i>
        <span>{{r.time}}</span>
        <i ng-class="heart" ng-click=""></i>
    </li>
</ul>

<input type="text" ng-model="ingredient" ng-change="filterByIngredient()" />

If you do filtering in view, angular does it in each digest cycle, however it's not needed unless "ingredient" changes. So, it is better to do it in controller.

Upvotes: 0

juanObrach
juanObrach

Reputation: 158

Pass through my ng-model input the property "ingredients" find in each object.

input(ng-model="ingredient.ingredients")
enter code here

and then, when I put a filter option in my ng-repeat list I can find only the object that contain the same ingredient write in the input tag.

ul(ng-repeat="r in recipes | filter:ingredient")

I hope that help you if you have the same problem

Upvotes: 1

probinson
probinson

Reputation: 361

Change the ng-model to ingredient.ingredients.

input(type="text" ng-model="ingredient.ingredients")

If you want strict equality change filter:ingredient to filter:ingredient:true

ul(ng-repeat="r in recipes | filter:ingredient:true")

Look at this.

Upvotes: 1

Related Questions