Angularjs - 如何计算' li'在列表和列表的宽度上加载

时间:2014-08-19 07:05:26

标签: html angularjs

检查我的PLNKR,因为您可以看到有10个menuitem,但计数显示为3。 我需要计算li的数量和ul的最终宽度。 请注意,我需要计算li,因为所有li都将根据安全组进行填充,因此列表不会包含所有json项。

HTML代码

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <script src="script.js"></script>
</head>

 <body ng-app="app">
 <div ng-controller="scrollController" >
 <input ng-click="myStyle={'margin-left': moveLeft()}" ng-disabled="leftdisabled" class="left" type="button" value="Move Left" />
 <div class="menucontainer left">
  <ul id="myMenuList" ng-style="myStyle">
    <li ng-repeat="item in items"> <a href="#">{{item.name}}</a>

    </li>

  </ul>
</div>
<input ng-click="myStyle={'margin-left': moveRight()}" ng-disabled="rightdisabled" class="left" type="button" value="Move Right" />
<br>
<br>
<br>
<br>
<p >Need help: there are total 12 menu item, i want to get count of LI and width of UL</p>
please note i dont need count of 'item', i need count of 'li' after it's populated in 'ul' as there will be some security groups based on that only 'li' will be populated
</div>

</body>
</html>

角色代码

var app = angular.module('app', []);

app.controller('scrollController', function($scope) {
$scope.marginLeft = 0;

$scope.myStyle = {'margin-left': '0px'};
var items = [];
$scope.items = [{name:"111",age:25},{name:"222",age:25},{name:"333",age:25},{name:"444",age:25},{name:"555",age:25},{name:"666",age:25},{name:"aaa",age:25},{name:"bbb",age:25},{name:"ccc",age:25},{name:"ddd",age:25}];


 //need help here
 $scope.mml=angular.element(document.getElementById('myMenuList'));
 alert($scope.mml.children.length);

})

2 个答案:

答案 0 :(得分:3)

如果您的控制器中有$timeout,那就太好了:

app.controller('scrollController', function($scope, $timeout) {

并且因为angular具有jqLite实现,您可以使用.find()查找目标ul中可用的列表项:

  $timeout(function(){
     alert($scope.mml.find('li').length);
  }, 1000);

Plunkr here.


根据您的评论,您可以这样使用clientWidth

$scope.mml[0].clientWidth

这可以为您提供所定位元素的实际宽度。

Updated plunkr...

答案 1 :(得分:1)

您可以创建指令,该指令将在最后重复的项目上触发传递函数。

app.directive('onLastRepeat', function($timeout) {
    return function (scope, elm, attrs) {
        if (scope.$last) {
            $timeout(function () {
                scope.$eval(attrs.onLastRepeat);
            });
        }
    };
});

HTML

<li ng-repeat="item in items" on-last-repeat="countLi()"> <a href="#">{{item.name}}</a></li>

控制器:

$scope.countLi = function(){
  $scope.mml=angular.element(document.getElementById('myMenuList'));
  alert($scope.mml.children().length);
}

您在这里更新了plunkr:http://plnkr.co/edit/4hRSj0axTcawamRCvVD6?p=preview