AngularJS Filter问题:仅比较字符串(substring)的一部分

时间:2014-04-08 09:45:58

标签: javascript html angularjs

当我使用字符串" home"过滤数据时发生问题。和"家123",如果我过滤" home"然后内容与" home 123"也选择了。这意味着布尔返回true,即使对于" home 123"如果我过滤" home"那是子串。 http://jsbin.com/jolik/1/edit

但是,如果我使用过滤器与不相关的字符串" home"和"产品"我得到了准确的结果。看到这个JS Bin演示http://jsbin.com/rusab/1/edit

请帮助解决此问题。提前感谢您的帮助。

的index.html:

<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>

  </head>

<body ng-controller="MyApp">
  <select ng-model="keyToDisplay" ng-options="key as key.key for key in keys"></select>
  <span>{{keyToDisplay.key}}</span>


  <div ng-repeat="item in data | filter:{'key':keyToDisplay.key}">
    <h3>{{item.key}}</h3>
    <p>{{item.value}}</p>
  </div>
  <hr />

</body>
</html>

工作代码:app.js

var app = angular.module('myapp', []);

app.controller('MyApp', ['$scope', function($scope) {
  $scope.data = [
    {key:"home",value:"hk1"},
    {key:"home",value:"hk2"},
    {key:"home",value:"hk3"},
    {key:"home",value:"hk4"},
    {key:"product",value:"pk1"},
    {key:"product",value:"pk2"},
    {key:"product",value:"pk3"},
    {key:"product",value:"pk4"},
    {key:"service",value:"sk1"},
    {key:"service",value:"hk2"},
    {key:"service",value:"hk3"},
    {key:"service",value:"hk4"}
  ];

  $scope.datafiltered = _.groupBy($scope.data, 'key');

  $scope.keys = _.unique($scope.data, 'key');

  $scope.keyToDisplay = $scope.keys[0];
}]);    

问题代码:app.js

var app = angular.module('myapp', []);

app.controller('MyApp', ['$scope', function($scope) {
  $scope.data = [
    {key:"home",value:"hk1"},
    {key:"home",value:"hk2"},
    {key:"home",value:"hk3"},
    {key:"home",value:"hk4"},
    {key:"home 123",value:"pk1"},
    {key:"home 123",value:"pk2"},
    {key:"home 123",value:"pk3"},
    {key:"home 123",value:"pk4"},
    {key:"service",value:"sk1"},
    {key:"service",value:"hk2"},
    {key:"service",value:"hk3"},
    {key:"service",value:"hk4"}
  ];

  $scope.datafiltered = _.groupBy($scope.data, 'key');

  $scope.keys = _.unique($scope.data, 'key');

  $scope.keyToDisplay = $scope.keys[0];
}]);    

1 个答案:

答案 0 :(得分:2)

用于完全等效使用extended filter

在过滤器参数后查看 true

  <div ng-repeat="item in data | filter:keyToDisplay.key:true">
    <h3>{{item.key}}</h3>
    <p>{{item.value}}</p>
  </div>
  <hr />

filter docs

的详细信息