2015-11-22 55 views
0

在AngularJS中,如何计算特定属性的出现次数(本例中为data-page)?计算属性发生次数

我有几个伪页面在刷卡时向用户显示,我希望防止页面计数器超过页面数量。我已经把我的容器,如下所示,但如果任何人有我如何能做到这一点更好的想法,我很开放的建议 -

我的HTML(样品) -

<body class="single single-post postid-5 single-format-standard ng-scope" data-ng-swipe-right="prevPage()" data-ng-swipe-left="nextPage()" data-ng-controller="bodyCtrl"> 
    <div id="main"> 
     <div class="container"> 

      <div class="allowed page page-1 visible" data-page="1"> 

       <div class="mask"></div> 
       <div class="inner"> 
        { page content } 
       </div> 

      </div> 

     </div> 
    </div> 
</body> 

我控制器 -

myApp.controller('bodyCtrl', function($scope){ 

    $scope.currentPage = 1; 
    $scope.getMaxPage = function(){ 
     { Not sure how??? } 
    } 
    $scope.maxPage = $scope.getMaxPage(); 

    $scope.nextPage = function(){ 
     $scope.currentPage = ($scope.currentPage >= $scope.maxPage) ? $scope.maxPage : $scope.currentPage + 1; 
    } 

    $scope.prevPage = function(){ 
     $scope.currentPage = ($scope.currentPage > 1) ? $scope.currentPage - 1 : 1; 
    } 

    $scope.isVisible = function(page){ 
     return ($scope.currentPage >= page); 
    } 

}); 

回答

2

我认为你可以使用jQuery,如果您正在使用的角度一起使用jQuery选择计数或你喜欢做下面去了。

//count the number of occurrences of the `data-page` attribute. 
var count = $('[data-page]').length; 

这里是一个DEMO

如果您不想使用jquery那么做,在普通的旧JavaScript的方式。

//select all element with the data-page attribute 
var elements = document.querySelectorAll('[data-page]'); 
var count = elements.length; // get the number of occurrences. 

这里是一个DEMO