Angular.js ng-repeat 回调

sno*_*h27 5 javascript angularjs angularjs-ng-repeat

完成后我需要发送回调ng-repeat,但我的解决方案不起作用。在我的最后一个解决方案中,我使用了一个指令来做到这一点。

标记:

<div class="results" ng-model="results">
    <div class="empl-card" ng-repeat="empl in employees | filter: searchQuery" callback-on-end="alert('callback')">
    ...
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

指示:

app.directive("callbackOnEnd", function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            if (scope.$last) {
                scope.$eval(attrs.callbackOnEnd);
            }
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

我哪里可能犯了错误?

Him*_*agi 1

为了实现这一点,您需要在控制器中创建一个方法,并在 ng-repeat 结束时调用该方法:

(function() {

  angular.element(document).ready(function() {
    var app = angular.module('myApp', []);

    app.controller("MyCtrl", function($scope, $timeout) {

      $scope.names = ['A', 'B', 'C', 'D'];

      $scope.onEnd = function() {
        alert('all done');
      };

    });

    app.directive("callbackOnEnd", function() {
      return {
        restrict: "A",
        link: function(scope, element, attrs) {
          if (scope.$last) {
            scope.$eval(attrs.callbackOnEnd);
          }
        }
      };
    });

    angular.bootstrap(document, ['myApp']);
  });


}());
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl" class="well">
  <h3 ng-repeat="name in names" callback-on-end="onEnd()">{{name}}</h3>
</div>
Run Code Online (Sandbox Code Playgroud)

或者你必须使用evaljavascript 代码

app.directive("callbackOnEnd", function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            if (scope.$last) {
                eval(attrs.callbackOnEnd);
            }
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

app.directive("callbackOnEnd", function() {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            if (scope.$last) {
                eval(attrs.callbackOnEnd);
            }
        }
    };
});
Run Code Online (Sandbox Code Playgroud)
(function() {

  angular.element(document).ready(function() {
    var app = angular.module('myApp', []);

    app.controller("MyCtrl", function($scope, $timeout) {

      $scope.names = ['A', 'B', 'C', 'D'];

      $scope.onEnd = function() {
        alert('all done');
      };

    });

    app.directive("callbackOnEnd", function() {
      return {
        restrict: "A",
        link: function(scope, element, attrs) {
          if (scope.$last) {
            eval(attrs.callbackOnEnd);
          }
        }
      };
    });

    angular.bootstrap(document, ['myApp']);
  });


}());
Run Code Online (Sandbox Code Playgroud)

在这里找到很好的解释: https ://stackoverflow.com/a/15671573/3603806