在控制器之前执行指令代码

时间:2014-07-03 11:16:28

标签: javascript angularjs angularjs-directive

您好我正在尝试创建一个显示加载框实现,但我似乎遇到了一些问题。到目前为止,这就是我所拥有的:

我创建了一个httpInterceptor:

   mainModule.factory('httpLoadingInterceptorSvc', ['$q', '$injector', 'EVENTS', function ($q, $injector, EVENTS) {
        var httpInterceptorSvc = {};

        httpInterceptorSvc.request = function (request) {
            var rootScope = $injector.get('$rootScope');
            rootScope.$broadcast(EVENTS.LOADING_SHOW);
            return $q.when(request);
        };

        httpInterceptorSvc.requestError = function (rejection) {
            hideLoadingBox();
            return $q.reject(rejection);
        };

        httpInterceptorSvc.response = function (response) {
            hideLoadingBox();
            return $q.when(response);
        };

        httpInterceptorSvc.responseError = function (rejection) {
            hideLoadingBox();
            return $q.reject(rejection);
        };

        function hideLoadingBox() {
            var $http = $injector.get('$http');

            if ($http.pendingRequests.length < 1) {
                var rootScope = $injector.get('$rootScope');
                rootScope.$broadcast(EVENTS.LOADING_HIDE);
            }
        }

        return httpInterceptorSvc;
    }]);

然后我将指令添加到httpProvideR的拦截器:

  $httpProvider.interceptors.push('httpLoadingInterceptorSvc');

然后我创建了一个指令:

 mainModule.directive('loadingDir', ['EVENTS', function (EVENTS) {
    var loadingDir = {
        restrict: 'E',
        templateUrl: 'App/scripts/main/directives/loading/LoadingDir.html'
    };

    loadingDir.link = function (scope, element) {
        element.hide();

        scope.$on(EVENTS.LOADING_SHOW, function () {
            element.show();
        });

        scope.$on(EVENTS.LOADING_HIDE, function () {
            element.hide();
        });
    };

    return loadingDir;
}]);

然后添加了一个简单的ajaxCall,用于警告控制器上的消息:

dataSvc.getCurrentDate().then(function(currentDate) {
        alert(currentDate);
    });

我在html页面上添加了edirective:

<loading-dir></loading-dir>

现在我的问题是指令代码在控制器代码之后执行,这使得反复使用直到页面被加载。有没有办法让指令代码在控制器之前执行?

1 个答案:

答案 0 :(得分:1)

您可以在页面前添加div:

<body>

    <div controller="beforeController">

        <loading-dir></loading-dir>

    </div>

[Rest of the page]

</body>

并且应该立即加载beforeController。