作用域$last或"empty scope"时的功能



我创建了一个指令:

.directive('repeatDone', function() {
  return function(scope, element, attrs) {
    if (scope.$last) {
      scope.$eval(attrs.repeatDone);
    }
  }
})

从Firebase下载列表并在屏幕上呈现时显示微调器:

<tr ng-repeat="task in tasks | filter:user.uid" class="item-unchecked" repeat-done="layoutDone()" ng-cloak>

以便在加载列表中的最后一个项目后(即,当加载设置为false时)微调器消失:

$scope.loading = true;
  $scope.layoutDone = function() {
    $timeout(function() {
      $scope.loading = false;
    }, 0);
  };

现在,这不包括列表为空的情况(即,每当我创建一个新的(空的)列表时)。如何将此特定场景添加到条件if (scope.$last)中?

我已经试过了:

  • if (!scope || scope.$last)
  • if (!scope.length || scope.$last)
  • if (scope === [] || scope.$last)

没有成功。

谢谢你的帮助!

这里有一个解决方案-Plunker。

JS-

app = angular.module("app", []);
app.controller("ctrl", ['$scope', '$timeout', function($scope, $timeout) {
  $scope.tasks = [{id: 0}, {id: 1}, {id: 2}, {id: 3}, {id: 4}];
  $scope.loading = true;
  $scope.layoutDone = function() {
    $timeout(function() {
      console.log("done");
      $scope.loading = false;
    }, 0);
  };
}]);
app.directive('repeatDone', function() {
  return function(scope, element, attrs) {
    if (scope.$last) {
      scope.$eval(attrs.repeatDone);
    }
  }
})
app.directive('emptyTasks', function() {
  return function(scope, element, attrs) {
    scope.$eval(attrs.emptyTasks);
  }
})

标记

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body ng-app="app" ng-controller="ctrl">
    <table>
      <tr ng-repeat="task in tasks track by $index" repeat-done="layoutDone()">
        <td>{{$index}}</td>
      </tr>
    </table>
    <div ng-if="tasks.length===0" empty-tasks="layoutDone()">Hello</div>
  </body>
</html>

这个想法是,如果任务的长度为0:,那么就有一个调用layoutDone的元素

<div ng-if="tasks.length===0" empty-tasks="layoutDone()">Hello</div>

ng-if表示每次创建div,因此调用layoutDone()。

这样做很奇怪,但它遵循了你的想法。:-)如果tasks为空或有一些元素,你可以看到"done"被写入控制台。

您在哪里使用

 $scope.loading = false

添加

&& tasks && tasks.length > 0

所以

<div ng-if="loading && tasks && tasks.length > 0">
I will not show if not loading, if task is null, or if there are no tasks avaiable
</div>

最新更新