在我的应用程序的$ rootScope中的所有部分加载后,如何运行自定义JavaScript?

时间:2014-03-30 22:27:45

标签: javascript jquery angularjs

我有一个用ng-app="blahApp"指定的应用。在应用程序内部有大约10个ng-include个,每个ng-include="'/url/to/template.html'"基于URL通过HTTP加载模板,例如$(document).ready();

在应用程序将所有部分加载到DOM后,如何执行单个函数?

我问的原因是因为加载的每个模板都有一些东西,否则(当不使用Angular时)依赖于对jQuery插件的单个调用,该插件在<!-- 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> 上启动页面上的所有项目。但是现在,document.ready不起作用,因为部分文件直到document.ready之后才加载。

{{1}}

1 个答案:

答案 0 :(得分:1)

正如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>