AngularJS:如何为ng-repeat中的被点击项目分配活动类?

时间:2015-08-09 17:36:45

标签: angularjs

在使用ng-repeat指令时,我对如何在单击的项目上显示.active类感到困惑。这是a Plunker

以下是我的观点:

<h4>Arctic Videos</h4>

<ul class="list-unstyled">
    <li class="clearfix" ng-repeat="item in videos" ng-class="{ active: $index }" style="padding-bottom: 2em;">
        <div style="float: left; position:relative;">
        <img class="img-thumbnail" ng-src="{{item.thumbUrl}}" width="100" height="68" alt="">
        </div>
        <h4><a href="#/videos/{{videos.indexOf(item)}}" ng-click="I AM NOT SURE WHAT TO PUT HERE">{{item.title}}</a></h4>
    </li>
</ul>

我的script.js

    var ArcticApp = angular.module('ArcticApp', ['ngRoute', 'ngSanitize']);

    ArcticApp.config(function($routeProvider){
    $routeProvider

        .when('/', {
            templateUrl: './partials/map.html',
            controller: 'MainController'
        })

        .when('/videos/:itemId', {
            templateUrl: './partials/videos.html',
            controller: 'VideoController'
        })

        .otherwise({
            redirectTo: '/'
        })
});

ArcticApp.controller('MainController', function($scope){

    $scope.message = "This is the map page!";
});

ArcticApp.controller('VideoController', function($scope, $routeParams, $sce){
        $scope.videos = [
  {
    "blockquote": "et sint quae\nqui odio fugit quia aut modi id maxime\nsequi qui et",
    "title": "Canada",
    "synopsis": "<p>Some text will go here and there. Some more will go here.</p><p>Yet even some more text will go here and there. yes, tehre's even more here.</p>",
    "id": 897,
    "thumbUrl": "http://placehold.it/100x68"
  },
  {
    "blockquote": "sit molestiae possimus ut in explicabo\nea autem saepe a iusto est exercitationem at\ndistinctio quia consectetur nulla vel maxime",
    "title": "USA",
    "synopsis": "<p>Some text will go here and there. Some more will go here.</p><p>Yet even some more text will go here and there. yes, tehre's even more here.</p>",
    "id": 471,
    "thumbUrl": "http://placehold.it/100x68"
  },
  {
    "blockquote": "recusandae natus minus est saepe alias\nvero amet quia natus voluptatem ut saepe dolor rem\nperspiciatis quia unde quia cum aliquam sint",
    "title": "Russia",
    "synopsis": "<p>some text can go here </p>",
    "id": 400,
    "thumbUrl": "http://placehold.it/100x68"
  }
];
        $scope.whichItem = $routeParams.itemId;
        $scope.trustAsHtml = $sce.trustAsHtml.bind($sce);
});

如何为点击的项目分配活动课程?

2 个答案:

答案 0 :(得分:0)

使用

ng-class="{ active: selectedVideo === item }"

并且

ng-click="selectVideo(item)"

在控制器中,添加

$scope.selectVideo = function(video) {
    $scope.selectedVideo = video;
}

答案 1 :(得分:0)

你可以像这样使用它

<li class="clearfix" ng-repeat="(key,item) in videos" ng-class="{ active:(condition) }" style="padding-bottom: 2em;">

key是迭代次数,condition可以是使活动类为true的任何布尔逻辑

喜欢

ng-class="{ active: 1==1 } 

在这种情况下,因为1 == 1为真,所以将打印活动类。