如何在angular js中添加ng-include回调到多个ng-include指令

时间:2014-09-11 04:50:16

标签: javascript angularjs angularjs-directive angularjs-scope

我有像这样的HTML

  <form ng-controller="testCtrl1">
    <div ng-include="'test/views/navigationbar.html'"></div>
    <div ng-include="'test/views/processnav.html'"></div>
    <div ng-include="'test/views/leftprocesstabs.html'"></div>
   </div>
</form>

我想编写通用方法来检查我所有的ng-include文件是否已加载。

加载所有文件后,我需要拨打服务器电话。

有没有办法在角度js中检查这个?

2 个答案:

答案 0 :(得分:4)

使用每个模板的onload并递增计数器。 如果表单只包含ng-include div,请使用beow代码获取计数,或编写一个函数来获取包含ng-include的div计数。

HTML

<form ng-controller="testCtrl1" id="includes">
    <div ng-include="'test/views/navigationbar.html'"  onload="load()"></div>
    <div ng-include="'test/views/processnav.html'" onload="load()"></div>
    <div ng-include="'test/views/leftprocesstabs.html'" onload="load()"></div>
   </div>
</form>

的Javascript

var templates = 0;
var length = $("#includes > div").length; 
$scope.load = function(){
    templates++;
    if(templates >= length){
        onLoadComplete()
    }

}
function onLoadComplete(){
    // all templates are loaded
}

答案 1 :(得分:2)

ng-include会触发通过模板缓存的请求。这是完成异步所以没有,角度无法为你提供所有模板加载时的触发器。

您可以将模板预取到缓存中并从那里处理事件......

例如,

// inject $q, $http, $templateCache to your controller 
...
var promises = [];
promises.push($http.get('test/views/navigationbar.html',{ cache : $templateCache }));
promises.push($http.get('test/views/processnav.html',{ cache : $templateCache }));
promises.push($http.get('test/views/leftprocesstabs.html',{ cache : $templateCache }));
$q.all(promises, function (data) { 
 console.log('All templates are loaded into the cache !');
});
...