使用 ng-repeat 指令时,在很多情况下,需要在其 render 完成后对 DOM 元素添加一些事件,如绑定 click 事件等。
一、ng-repeat 使用背景
使用 ng-repeat,AngularJs会遍历users数据对象,来 render 渲染出这个table中的内容。
Id | Name | Salary |
---|---|---|
{{user.Id}} | {{user.Name}} | {{user.Salary}} |
二、使用 $timeout 实现在render完成之后,执行Js脚本
说明:这里会用到:自定义指令、 $timeout、 link 函数,详细介绍请自行查阅官方文档。
$timeout : 不会执行,直到元素存在。
第一步:为当前的 app 自定义一个 directive
app.directive('onRendered', function ($timeout) { return { restrict: 'A', link: function(scope, element, attr) { if (scope.$last === true) { $timeout(function() { scope.$emit('event-ngRepeat-finished'); }); } } }; });
第二步:在需要监听的地方加上该 directive
{{user.Id}} {{user.Name}} {{user.Salary}}
第三步:为自定义事件添加触发执行函数
$scope.$on('event-ngRepeat-finished', function (event) { // write your code here. });
三、用法举例
- {{item}}
var myApp = angular.module('myApp', []); //myApp.directive('myDirective', function() {}); //myApp.factory('myService', function() {}); myApp.directive('onFinishRender', ['$timeout', '$parse', function ($timeout, $parse) { return { restrict: 'A', link: function (scope, element, attr) { if (scope.$last === true) { $timeout(function () { scope.$emit('ngRepeatFinished'); if ( !! attr.onFinishRender) { $parse(attr.onFinishRender)(scope); } }); } if (!!attr.onStartRender) { if (scope.$first === true) { $timeout(function () { scope.$emit('ngRepeatStarted'); if ( !! attr.onStartRender) { $parse(attr.onStartRender)(scope); } }); } } } } }]); myApp.controller('MyCtrl', function($scope){ $scope.items = [ "lorem", "ipsum", "dolor", "sit", "amet,", "consectetur", "adipiscing" ]; $scope.callMyCustomMethod = function () { console.log('Method called by the directive, when finished rendering'); } $scope.callMyCustomMethod2 = function () { console.log('Method2 called by the directive, when starting rendering'); } $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) { console.log('Event captured in the controller, when finished rendering'); }); $scope.$on('ngRepeatStarted', function (ngRepeatStartedEvent) { console.log('Event captured in the controller, when started rendering'); }); });
转载请注明,
原文出处: http://lixh1986.iteye.com/blog/2429307
引用:
https://stackoverflow.com/questions/20155733
https://github.com/angular/angular.js/issues/734
http://www.jomendez.com/2015/02/05/ng-repeat-onfinishrender-directive-angularjs/
-