簡體   English   中英

如何避免ng-init的角度?

[英]How to avoid ng-init in angular?

當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不會監視源數組的修改。 有任何提示如何正確執行嗎?

檢查ng-repeats $ 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
  }
})

您可以在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>

另請參閱此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>

這個jsfiddle

由於您已經將(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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM