Reputation: 158
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
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
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