1

如何根据 $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如果 tagged 的​​结果为真,则附加该类。

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是错误的,但我以此为例来说明知识差距。

4

1 回答 1

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>

柱塞

于 2013-07-14T10:31:59.933 回答