gpt4 book ai didi

javascript - 在 Controller 之前执行指令代码

转载 作者:行者123 更新时间:2023-12-03 12:18:33 24 4
gpt4 key购买 nike

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

我创建了一个 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,用于在 Controller 上发出警报消息:

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

我将指令放在 html 页面上:

<loading-dir></loading-dir>

现在我的问题是指令代码在 Controller 代码之后执行,这使得指令在页面加载之前相对有用。有什么方法可以使指令代码在 Controller 之前执行吗?

最佳答案

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

<body>

<div controller="beforeController">

<loading-dir></loading-dir>

</div>

[Rest of the page]

</body>

beforeController 应该立即加载。

关于javascript - 在 Controller 之前执行指令代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24552252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com