让ng-class改变整数ng-repeat

时间:2017-12-01 13:24:01

标签: html angularjs

我正在设置一组页面指示器,我只想要与当前查看的页面对应的指示器将“活动”类应用于它。
我已经设置了一个控制器来确定哪个指标应该应用'active'类,使用html中的ng-class:

<div class="progress-buttons" ng-controller="progressButtonCtrl">
    <div ng-repeat="(skey,page) in pages" class="button" ng-class="ctrlClass" ng-attr-id="{{'nav-'+(skey+1)}}">
         <div ng-switch="page.titletext || '_undefined_'" >      
              <span ng-switch-when="_undefined_">{{skey+1}}</span>
         </div>
    </div>
</div>

这是控制器...

app.controller('progressButtonCtrl', ['$scope', '$routeParams', '$http', 'content', function($scope, $routeParams, $http, content) {

    function initScope() {
        $scope.pageId = $routeParams.pageId; 
        $scope.ctrlClass = "";

        content.success(function(data) {

            $scope.pages = data;
            angular.forEach($scope.pages, function(value, key) {
                console.log("$scope.pageId = "+$scope.pageId);
                console.log("page id (value.id) = "+value.id);
                if ($scope.pageId == value.id) {
                    console.log("active class applied...");
                    $scope.ctrlClass = "active";
                }
            });
        });
    }

    initScope();

}]);

我'控制台'记录了当前页面的id值和所有页面的id值;他们按照我的预期输出为1和1,2,3。但是,尽管“应用了活跃的类......”只获得一次输出,但“活动”类应用于所有指标。我猜我每个指标都需要一个唯一的ng-class标识符,但是当实例数量变化时,如何在ng-repeat中执行此操作?

如果将“有效”课程仅应用于当前查看的页面,我应该采取哪些不同的做法?

感谢。

1 个答案:

答案 0 :(得分:1)

您应该将其分配给特定的数组(页面)元素,而不是范围var。

angular.forEach($scope.pages, function(value, key) {
   console.log("$scope.pageId = "+$scope.pageId);
   console.log("page id (value.id) = "+value.id);
   if ($scope.pageId == value.id) {
      console.log("active class applied...");
      value.class = "active";
   }
});

和你的HTML:

<div ng-repeat="(skey,page) in pages" class="button" ng-class="page.class" ng-attr-id="{{'nav-'+(skey+1)}}">
   <div ng-switch="page.titletext || '_undefined_'" >      
      <span ng-switch-when="_undefined_">{{skey+1}}</span>
   </div>
</div>

我建议你这样做:

app.controller('progressButtonCtrl', ['$scope', '$routeParams', '$http', 'content', function($scope, $routeParams, $http, content) {

    function initScope() {
        $scope.pageId = $routeParams.pageId;

        content.success(function(data) {
            $scope.pages = data;
        });
    }

    initScope();

}]);

HTML:

<div class="progress-buttons" ng-controller="progressButtonCtrl">
    <div ng-repeat="(skey,page) in pages" class="button" ng-class="::{'active':pageId == page.id}" id="::{{'nav-'+(skey+1)}}">
         <div ng-switch="page.titletext || '_undefined_'" >      
              <span ng-switch-when="_undefined_">{{skey+1}}</span>
         </div>
    </div>
</div>

ng-class="::{'active':pageId == page.id}"开头的::符号表示单向数据绑定。您可以在https://toddmotto.com/angular-one-time-binding-syntax/

更多地阅读相关内容