当数组长度为零时显示ng-show

时间:2014-04-15 06:56:28

标签: angularjs

我是AngularJS的初学者。我正在尝试显示" No Tag Found"在过滤过程中借助" ng-show "。

JS:

function simpleController($scope)
{
$scope.tags = ['HTML','CSS','Jquery','Bootstrap','AngularJS'];
}

HTML:

<div ng-controller="simpleController">
<input  class="txt" type="text" ng-model="nameText" /> 
<div>
 <ul>
  <li ng-repeat="myKeys in tags| filter:nameText">{{myKeys}}</li>
 </ul>
<div ng-show="!tags.length">No Tag Found</div>
</div>
</div>

当我输入除数组值之外的任何值时,我无法获得&#34;找不到标记&#34;使用上面的代码。请帮忙。感谢。

5 个答案:

答案 0 :(得分:43)

如果您使用ng-repeat进行过滤,则必须为您ng-show应用相同的过滤器。如果不这样做,ng-show将始终引用完整数组:

<div ng-show="!(tags| filter:nameText).length">No Tag Found</div>

工作小提琴:http://jsfiddle.net/HB7LU/3149/

答案 1 :(得分:19)

最好使用ng-hide:

<div ng-hide="tags.length">No Tag Found</div>

答案 2 :(得分:11)

 <div class="box" ng-show="team_stores.length > 0" >   

为我工作

答案 3 :(得分:3)

创建过滤器的简便方法...演示如下

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myctrl', function ($scope) {

    $scope.friends = [
      { name: "Peter", age: 20 },
      { name: "Pablo", age: 55 },
      { name: "Linda", age: 20 },
      { name: "Marta", age: 37 },
      { name: "Othello", age: 20 },
      { name: "Markus", age: 32 }
    ];

});
&#13;
<!DOCTYPE html>
<html>
<head>
<title>welcome</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myctrl">
   Name: <input ng-model="filter" type="text" />
    <ul>
        <li ng-repeat="friend in friends |filter:filter">{{friend.name}}</li>

        <li ng-show="!(friends| filter:filter).length">data not found</li>
        <!--<link ng-repeat="friend in friends|filter:isActive ">-->
    </ul>


</body>
</html>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您也可以尝试使用过滤器服务,如下所示:$filter('filter')(array, expression, comparator),此服务返回新数组 你可以看到http://code.angularjs.org/1.2.16/docs/api/ng/filter/filter