0

场景: 我有一个项目数组,每个项目都有属性(模型,id),

$scope.arrayOfItems = [{
                         model : 'L_',
                         id : 01
                       },
                       {
                         model : 'L_',
                         id : 2323
                       },
                       {
                         model : 'L_',
                         id : 434
                       }
                    ];

对于每个项目,这两个属性都合并形成一个项目标签。我正在尝试过滤两个视觉合并的表达式

{{::item.model}}{{::item.id}}

model = 'L_';
id    = 03;

所以结果是L_03

如果我希望在输入字段中搜索项目标签“L_2323” 并键入“L_”,然后输入 ID,则所有列表项都会消失。

我希望能够输入“L_2323”并显示相应的列表项

我知道我可以遍历并合并所有模型和 id 并将其放入控制器中的一个数组中,并在主项的循环中显示该数组的每个项,但这似乎是一个浪费的解决方案,我正在尝试解决以更务实的方式解决问题

我已经添加了这个 bug Codepen 的
codepen

4

2 回答 2

1

基本的搜索代码可以是这样的:

const arr = [{
  model: 'L_',
  id: '01'
}, {
  model: 'L_',
  id: '2323'
}, {
  model: 'L_',
  id: '434'
}];

const search = function(searchTerm) {
  return arr.filter(item => {
    const fullName = item.model + item.id;
    return fullName.includes(searchTerm);
  })
}

const searResult1 = search('01');
console.log(searResult1);

const searResult2 = search('L_');
console.log(searResult2);

https://jsfiddle.net/90Lc7dt8/8/

我们在这里做的是:

  1. 创建一个fullName包含您要搜索的信息的变量
  2. 使用过滤器返回匹配模式的项目

现在您只需要输入的角度代码。

  1. 用于ng-model输入
  2. 将搜索功能作为手表功能
  3. 用于ng-repeat列出结果

这是关于 codepen 的角度示例: https ://codepen.io/bergur/pen/yqKaKw?editors=1010#0

于 2018-08-01T10:42:55.467 回答
1

只需编写一个自定义过滤器来扫描数组以查找匹配项model + id。这是它的外观的快速演示:

var app = angular.module('myApp', []);
app.filter('myFilter', function() {
  return function(arrayOfItems, input) {
    var res = [];
    if (input) {
      for (var i = 0; i < arrayOfItems.length; i++) {
        var item = arrayOfItems[i];
        if ((item.model + item.id).match(input)) { // match
          res.push(item);
        }
      }
      // don't return an empty array if nothing was found
      return (res.length > 0) ? res : arrayOfItems; 
    }
    return arrayOfItems; // default (no input given)
  };
});

app.controller('namesCtrl', function($scope) {
  $scope.arrayOfItems = [{
      model: 'L_',
      id: 01
    },
    {
      model: 'L_',
      id: 2323
    },
    {
      model: 'L_',
      id: 434
    }
  ];
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>
  <div ng-app="myApp" ng-controller="namesCtrl">

    <span>Filter your search : 
      <input type="text" ng-model="searchFilter">
      {{searchFilter}}
    </span>
    
    <hr>

    <div ng-repeat="item in arrayOfItems | myFilter: searchFilter">
      {{item.model}}{{item.id}}
    </div>
  </div>
</body>
</html>

于 2018-08-01T10:48:26.447 回答