如何同时angularjs完成渲染UI注册事件 [英] How to register event while angularjs finish rendering UI
问题描述
例如
function SomeCtrl($scope) {
$scope.list = [...]
$scope.click = function() {
var newdata = $someservice.get()
angular.forEach(newdata, function(v){
$scope.list.push(v)
})
//???
}
}
HTML
<div style="height:400" id="main">
<div ng-repeat="row in list">
...
</div>
</div>
我的问题是,当我将数据添加到 $ scope.list
,我怎样才能得到一个通知,而数据更新到UI,因为我想主要的div总是滚动底部?
My question is when I add data to $scope.list
, how Can I get a notify while data is updated to UI because I want the main div always scrolling to bottom?
推荐答案
试试这个
var module = angular.module('testApp', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
}
}
}
});
请注意,我没有用。就绪(),而是把它包在$超时。 $超时确保它的时候NG重复的元素都真正完成渲染执行(因为$超时将执行在当前消化周期结束 - 这也将调用$内部应用,不同的setTimeout)。纳克重复完成操作后,我们使用$发出发出一个事件外范围(兄弟姐妹和父母范围)。
Notice that I didn't use .ready() but rather wrapped it in a $timeout. $timeout makes sure it's executed when the ng-repeated elements have REALLY finished rendering (because the $timeout will execute at the end of the current digest cycle -- and it will also call $apply internally, unlike setTimeout). So after the ng-repeat has finished, we use $emit to emit an event to outer scopes (sibling and parent scopes).
然后在你的控制器,你可以用$赶上它:
And then in your controller, you can catch it with $on:
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
//you also get the actual event object
//do stuff, execute functions -- whatever...
});
这篇关于如何同时angularjs完成渲染UI注册事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!