【问题标题】:filter an array with objects with Angular.js使用 Angular.js 过滤包含对象的数组
【发布时间】:2015-04-07 23:37:36
【问题描述】:

标题

您好,我的 Angular.js 控制器中有这个带有对象的 $scope 数组:

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

]

然后我在 $scope.recipe 中重复 ech 对象

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()")

并将此输入与 ng-model 一起使用以过滤我的 ng-repeat

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

问题是。如何仅过滤每个对象的每个“成分”属性中的单词。

谢谢。

【问题讨论】:

    标签: angularjs-ng-repeat javascript-objects ng-repeat angularjs-filter


    【解决方案1】:

    将 ng-model 更改为成分.ingredients。

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

    如果您想要严格相等,请将 filter:ingredient 更改为 filter:ingredient:true

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

    this

    【讨论】:

      【解决方案2】:

      通过我的 ng-model 输入在每个对象中找到的属性“ingredients”。

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

      然后,当我在我的 ng-repeat 列表中放置一个过滤器选项时,我只能在输入标签中找到包含相同成分的对象。

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

      如果你有同样的问题,希望对你有所帮助

      【讨论】:

        【解决方案3】:

        这种过滤方式会减慢您的运行速度。更好的过滤方式如下:

        在控制器中:

        $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();
        

        在视图中:

        <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()" />
        

        如果您在视图中进行过滤,角度会在每个摘要周期中进行,但是除非“成分”发生变化,否则不需要它。因此,最好在控制器中进行。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-07-30
          • 1970-01-01
          • 2014-09-02
          • 2021-08-28
          • 1970-01-01
          • 2017-01-28
          • 2022-08-15
          • 2016-10-18
          相关资源
          最近更新 更多