我有一个用ng-app="blahApp"
指定的应用程序。在应用程序内部,有十个左右的ng-include
,每个都根据URL通过HTTP加载模板,例如 ng-include="'/url/to/template.html'"
.
如何在应用将所有部件加载到 DOM 后执行单个函数?
我问的原因是因为加载的每个模板都有一些东西,否则(不使用 Angular 时)依赖于对 jQuery 插件的单个调用,该插件启动$(document).ready();
页面上的所有项目。但是现在,document.ready不起作用,因为部分直到document.ready之后的一段时间才会加载。
<!-- HTML: -->
<div id="tabs" ng-app="reportTabsApp" ng-controller="RootController">
<!-- Load a bunch of partials here with ng-include -->
</div>
<!-- my Angular code: -->
<script>
var reportTabsApp = angular.module("reportTabsApp", []);
reportTabsApp.controller('RootController', function($scope, $rootScope) {
console.log($scope); // this works
console.log($rootScope); // this works
$scope.$on("$viewContentLoaded", function() {
console.log(" -- VIEW CONTENT LOADED!!"); // This never happens.
});
$rootScope.$on("$viewContentLoaded", function() {
console.log(" -- VIEW CONTENT LOADED!!"); // This also never happens.
});
});
</script>
正如 Eliran 在评论中建议的那样,答案是任意决定何时完成所有部分的加载。我想出了这个:
<script>
var yourApp = angular.module("yourApp", []);
yourApp.controller('YourController', function($scope) {
$scope.includeCounter = 0;
$scope.partials = [
'/path/to/template1.html',
'/path/to/template2.html',
'/path/to/template3.html'
// etc...
];
// in your html you use ng-repeat to repeat an element, and on each of
// those elements you have ng-include to load the above partials.
$scope.$on("$includeContentLoaded", function() {
$scope.includeCounter++;
if ($scope.includeCounter == $scope.partials.length) { // if all partials loaded.
console.log(" -- ALL PARTIALS LOADED!!");
// do what you need now that all partials are loaded.
}
});
});
</script>