在控制器前执行指令代码

Execute directive code before controller

本文关键字:指令 代码 执行 控制器      更新时间:2023-09-26

嗨,我试图创建一个显示加载框实现,但我似乎有一些问题。以下是目前为止的内容:

我已经创建了一个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页面上:

<loading-dir></loading-dir>

现在我的问题是指令代码在控制器代码之后执行,这使得指令相对有用,直到页面加载。是否有任何方法使指令代码在控制器之前执行?

你可以在你的页面前添加一个div:

<body>
    <div controller="beforeController">
        <loading-dir></loading-dir>
    </div>
[Rest of the page]
</body>