事件 – 当ng-repeat完成时调用函数

前端之家收集整理的这篇文章主要介绍了事件 – 当ng-repeat完成时调用函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想实现的基本上是一个“重复完成渲染”处理程序。我能够检测它什么时候完成,但我不知道如何从它触发一个函数

检查小提琴:http://jsfiddle.net/paulocoelho/BsMqq/3/

JS

  1. var module = angular.module('testApp',[])
  2. .directive('onFinishRender',function () {
  3. return {
  4. restrict: 'A',link: function (scope,element,attr) {
  5. if (scope.$last === true) {
  6. element.ready(function () {
  7. console.log("calling:"+attr.onFinishRender);
  8. // CALL TEST HERE!
  9. });
  10. }
  11. }
  12. }
  13. });
  14.  
  15. function myC($scope) {
  16. $scope.ta = [1,2,3,4,5,6];
  17. function test() {
  18. console.log("test executed");
  19. }
  20. }

HTML

  1. <div ng-app="testApp" ng-controller="myC">
  2. <p ng-repeat="t in ta" on-finish-render="test()">{{t}}</p>
  3. </div>

回答:
从整理工作的小提琴:http://jsfiddle.net/paulocoelho/BsMqq/4/

  1. var module = angular.module('testApp',function ($timeout) {
  2. return {
  3. restrict: 'A',attr) {
  4. if (scope.$last === true) {
  5. $timeout(function () {
  6. scope.$emit(attr.onFinishRender);
  7. });
  8. }
  9. }
  10. }
  11. });

注意,我没有使用.ready(),而是包装在$ timeout。 $ timeout确保当ng-repeated元素完成渲染(因为$ timeout将在当前摘要周期结束时执行)时执行它,并且它也会在内部调用$ apply,与setTimeout不同。所以在ng-repeat完成后,我们使用$ emit向外部范围(同级和父级范围)发出一个事件。

然后在你的控制器中,你可以抓住$ on:

  1. $scope.$on('ngRepeatFinished',function(ngRepeatFinishedEvent) {
  2. //you also get the actual event object
  3. //do stuff,execute functions -- whatever...
  4. });

用html看起来像这样:

  1. <div ng-repeat="item in items" on-finish-render="ngRepeatFinished">
  2. <div>{{item.name}}}<div>
  3. </div>

猜你在找的Angularjs相关文章