如何根据列表项长度显示链接元素

时间:2016-04-06 13:09:05

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我们需要显示所有列表项,如果列表长度超过4我们需要显示" show"链接否则隐藏"显示"链接。

DEMO:

HTML:

<div ng-controller="MyCtrl">
  <ul class="scrollbar" ng-class="{'noscrollbar' : scrollBar}">
  <li ng-repeat="x in names">{{ x.name + ', ' + x.country }}</li>
</ul>
<a ng-click="a()">{{text}}</a>
</div>

JS:

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

function MyCtrl($scope) {
    $scope.names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}];

$scope.showText=true;
$scope.scrollBar=false;
$scope.text='show';
$scope.a=function()
{
alert("call");
$scope.showText=!$scope.showText;
$scope.scrollBar=!$scope.scrollBar;
$scope.text=='show' ? $scope.text='less' : $scope.text='show';

};
}

CSS:

.scrollbar
{
  max-height:150px;
  overflow-y:scroll;
  width:200px;
}

.noscrollbar
{
    max-height:100%;
    overflow:auto;
}

如何显示&#39; show&#39;基于列表项长度的链接元素

1 个答案:

答案 0 :(得分:0)

您可以在此使用ng-show / ng-if

<a ng-click="a()" ng-show="names.length > 4">{{text}}</a>

注意

如果你想在这里使用ng-if,那么你需要在对象中加入text变量以确保跟随Dot规则。

<a ng-click="a()" ng-if="names.length > 4">{{model.text}}</a>