在$ location.search()参数AngularJS上过滤结果集

时间:2013-07-14 01:23:19

标签: javascript angularjs

如何在$ location.search()参数上过滤我的结果集?

<div ng-repeat="tag in tags">
  <div ng-class="{active:tagged(tag.id)}" ng-click="filter(tag.id)">
    {{album.title}}
  </div>
</div>

如果标记的结果为真,则附加类active

filter('tagged', function () {
  return function (id) {
    //Assume "tags" is also the name of the parameter.
    //"tags" is being set by $location.search({tags:['123','456','789']});
    return ($location.search().tags.indexOf(id) != -1)?true:false;
  };
});

ng-class内的惯例是错误的,但我用它来证明知识差距。

1 个答案:

答案 0 :(得分:2)

我认为您不能在ng-class表达式中使用过滤器函数,但您只需在控制器中定义tagged函数:

app.controller('AppController',
    [
      '$scope',
      '$location',
      function($scope, $location) {
        $location.search('tags', [1, 3]);

        $scope.tags = [
          {id: 1, title: "Can't Hold Us"},
          {id: 2, title: "Just Give Me A Reason"},
          {id: 3, title: "Mirrors"},
          {id: 4, title: "Get Lucky"},
        ];

        $scope.tagged = function(id){
          return $location.search().tags.indexOf(id) !== -1;
        };

      }
    ]
  );
<body ng-controller="AppController">

  <div ng-repeat="tag in tags">
    <div ng-class="{active:tagged(tag.id)}">
      {{tag.title}}
    </div>
  </div>

</body>

PLUNKER