我正在寻找一种方法来执行代码,当我添加更改一个$ scope变量,在这种情况下,$ scope.results。我需要这样做,以便调用一些遗留代码,需要项目在DOM中,然后才能执行。
我真正的代码是触发AJAX调用,并更新范围变量为了更新ui。所以我目前我的代码是在我推送到范围后立即执行,但遗留代码失败,因为dom元素尚未可用。
我可以添加一个丑陋的延迟与setTimeout(),但这并不保证DOM是真正准备好了。
我的问题是,有什么办法,我可以绑定到一个“呈现”的事件?
var myApp = angular.module('myApp',[]); myApp.controller("myController",['$scope',function($scope){ var resultsToLoad = [{id: 1,name: "one"},{id: 2,name: "two"},{id: 3,name: "three"}]; $scope.results = []; $scope.loadResults = function(){ for(var i=0; i < resultsToLoad.length; i++){ $scope.results.push(resultsToLoad[i]); } } function doneAddingToDom(){ // do something awesome like trigger a service call to log } }]); angular.bootstrap(document,['myApp']);
链接到模拟代码:http://jsfiddle.net/acolchado/BhApF/5/
提前致谢!
The 07000 queue is used to schedule work which needs to occur outside of current stack frame,but before the browser’s view render. — 07001
好吧,那么什么是“栈帧”? Github的评论揭示了更多:
if you enqueue from a controller then it will be before,but if you enqueue from directive then it will be after. — 07002
上面,Misko正在讨论何时运行由$ evalAsync排队执行的代码,与何时通过Angular更新DOM相关。我建议阅读前面的两个Github评论,以获得完整的上下文。
因此,如果代码使用$ evalAsync从指令排队,它应该在DOM被Angular操纵之后,但在浏览器呈现之前运行。如果您需要在浏览器渲染后运行某些内容,或者在控制器更新模型之后使用$ timeout(…,0);
参见http://stackoverflow.com/a/13619324/215945,它也有一个使用$ evalAsync()的例子。