如何避免角度的ng-init?

时间:2016-07-08 10:34:39

标签: angularjs

我想在ng-repeat集合为空时显示消息,即:

<div ng-init="filteredArray=(array|filter:{...})">
    <h1 ng-if="!filteredArray.length">Empty array</h1>
    <table ng-if="filteredArray.length">
        <tr ng-repeat="element in filteredArray">
            <td>{{element}}</td>
        </tr>
    </table>
</div>

问题是ng-init不会监视源阵列的修改。任何暗示如何正确地做到这一点?

3 个答案:

答案 0 :(得分:1)

检查重复$ last以显示如下信息

<div ng-repeat="n in data track by $index">
   <h1 ng-if="$last">Empty array</h1>

</div>

在您的情况下,您可以在表格级别设置变量,然后将其设置为$ last,当它变为真时,您的消息将显示如下

<body ng-app="app" ng-controller="ctrl">
    <div ng-init='counter=false'>
         <h1 ng-if='counter'>Empty array</h1>
      <table ng-if="myData.length">
        <tbody>
          <tr ng-repeat="element in myData track by $index" ng-init="counter=$last">
            <td>{{element}}
            <ng-if ng-init='sync($last)'/>
            </td>
          </tr>
        </tbody>
      </table>

    </div>
  </body>

您的控制器应如下所示

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

app.controller('ctrl',function($scope){

  $scope.myData=['a','b','c']
  $scope.sync=function(val)
  {
    alert(val)
    $scope.counter=val
  }
})

答案 1 :(得分:1)

您只需在ng-repeat中创建已过滤的变量,然后使用该变量:

<div>
    <h1 ng-if="!filteredArray.length">Empty array</h1>
    <table ng-if="filteredArray.length">
        <!-- here angular assigns the filtered array to the 'filteredArray' variable, 
        which then can be used -->
        <tr ng-repeat="element in filteredArray=(array|filter:{...})">
            <td>{{element}}</td>
        </tr>
    </table>
</div>

另见this jsfiddle

修改

如果你不喜欢丑陋的表情,你也可以这样做:

function myController ($scope, $filter) {
    $scope.$watch("theFilter", function (val) {
        $scope.filteredArray = $filter("filter")($scope.array, val);
    });
}

在你的HTML中:

<tr ng-repeat="element in filteredArray">
    ..
</tr>

签入this jsfiddle

答案 2 :(得分:0)

由于您已将(array|filter:{...})值存储到filteredArray,因此无法在模板中对其进行修改。

您应该在模板中重复(array|filter:{...})代码。

<h1 ng-if="!(array|filter:{...}).length">Empty array</h1>
<table ng-if="(array|filter:{...}).length">
    <tr ng-repeat="element in (array|filter:{...})">
        <td>{{element}}</td>
    </tr>
</table>