如何将ng-repeat过滤器移动到控制器中并在用户点击时应用“活动”类?

时间:2016-07-28 15:55:57

标签: angularjs angularjs-filter angularjs-ng-click angularjs-ng-class

我有一个标签式滑块,可以通过选择选项卡来切换滑块的视图,该选项卡按属性过滤ng-repeat。

当用户在标签之间点击时,如何将过滤器移动到控制器并应用“活动”类?

HTML:

<section class="foodTabSlider" data-ng-controller="sliderCtrl">
  <ul role="list">
    <li ng-click="myFilter = {featured:true}">Featured</li>
    <li ng-click="myFilter = {popular:true}">Popular</li>
    <li ng-click="myFilter = {special:true}">Special</li>
  </ul>
  <figure lightslider id="content-slider" class="content-slider">
    <figure role="listitem" data-ng-repeat="food in foods | filter:myFilter">
      <img src="{{ food.img }}" class="img-responsive">
      <figcaption>{{ food.figcaption }}</figcaption>
    </figure>
  </figure>
</section>

控制器:

'use strict';

angular.module('myApp').controller('sliderCtrl', function sliderCtrl($scope, foodSlider) {

  $scope.foods = foodSlider;  

  };

});

该服务的片段:

angular.module('myApp').factory('foodSlider', function() {
  var factory =
  [
    {
      img: 'images/food-1.png',
      figcaption: 'caption 1',
      featured: true,
      special: true
    },
    {
      img: 'images/food-2.png',
      figcaption: 'caption 2',
      popular: true,
      featured: true
    },
    {
      img: 'images/food-3.png',
      figcaption: 'caption 3',
      special: true
    }

  ]

    return factory;
});

1 个答案:

答案 0 :(得分:0)

以下是您的期望?

<section class="foodTabSlider" data-ng-controller="sliderCtrl">
  <ul role="list">
    <li ng-click="myFilter = {featured:true}"
        ng-class="{'active':myFilter.featured}">Featured</li>
    <li ng-click="myFilter = {popular:true}
        ng-class="{'active':myFilter.popular}"">Popular</li>
    <li ng-click="myFilter = {special:true}"
        ng-class="{'active':myFilter.special}">Special</li>
  </ul>
  <figure lightslider id="content-slider" class="content-slider">
    <figure role="listitem" data-ng-repeat="food in foods | filter:myFilter">
      <img src="{{ food.img }}" class="img-responsive">
      <figcaption>{{ food.figcaption }}</figcaption>
    </figure>
  </figure>
</section>

修改

你可以把

$scope.myFilter = {featured:true};

在您的控制器中,以便最初激活第一个。

或者您可以使用ng-init:

<section class="foodTabSlider" data-ng-controller="sliderCtrl">
  <ul role="list" ng-init="myFilter = {featured:true}">
    <li ng-click="myFilter = {featured:true}"
        ng-class="{'active':myFilter.featured}">Featured</li>
    <li ng-click="myFilter = {popular:true}
        ng-class="{'active':myFilter.popular}"">Popular</li>
    <li ng-click="myFilter = {special:true}"
        ng-class="{'active':myFilter.special}">Special</li>
  </ul>
  <figure lightslider id="content-slider" class="content-slider">
    <figure role="listitem" data-ng-repeat="food in foods | filter:myFilter">
      <img src="{{ food.img }}" class="img-responsive">
      <figcaption>{{ food.figcaption }}</figcaption>
    </figure>
  </figure>
</section>