반응형
각도 응용 프로그램 시작 시 코드 실행
Angular 부팅 시 자바스크립트 코드를 실행할 수 있는 방법이 있습니까?JS 어플리케이션?앱 지시/컨트롤러보다 먼저 실행해야 하는 몇 가지 공통 코드가 있습니다.루트에 얽매이고 싶지 않고ng-view
이 솔루션이 일반 솔루션이 되어야 합니다.ng-app
.
Module Config를 사용할 수 있을 것 같아서 실제로 사용해 보았습니다만, 서비스를 호출하려고 합니다.모듈 로드에서는 액세스 할 수 없을 것 같습니다.
이렇게 하면 되는데
var app = angular.module('myApp',[]);
app.run(function($rootScope) {
//.....
});
쇼트 버전
를 사용해야 합니다.module.run(initializationFn)
실제 메서드는 서비스에 의존할 수 있습니다.다음과 같이 종속성을 주입할 수 있습니다.
var app = angular
.module('demoApp', [])
.run(['$rootScope', function($rootScope) {
$rootScope.bodyClass = 'loading';
// Etc. Initialize here.
}]);
이 예에서는 초기화가 다음 항목에 따라 달라집니다.$rootScope
서비스 등을 삽입할 수도 있습니다.
긴 버전
관련 문서는 다른 (탁월한) 답변과 마찬가지로 다소 간결합니다.좀 더 자세한 예시로 결합해 보겠습니다. 이 예시는 또한 어떻게 주사하는지를 보여줍니다.factory
에서 생성된 서비스initializationFn
:
var app = angular.module('demoApp', []);
// Service that we'll also use in the .run method
app.factory('myService', [function() {
var service = { currentItem: { started: new Date() } };
service.restart = function() {
service.currentItem.started = new Date();
};
return service;
}]);
// For demo purposes
app.controller('demoCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.header = 'Demo!';
$scope.item = myService.currentItem;
$scope.restart = myService.restart;
}]);
// This is where your initialization code goes, which
// may depend on services declared on the module.
app.run(['$window', 'myService', function($window, myService) {
myService.restart();
$window.alert('Started!');
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller='demoCtrl' ng-cloak>
<h1>{{ header }}</h1>
<p>Current item started: {{ item.started }}</p>
<p><button ng-click="restart()">Restart</button></p>
</div>
모듈 API에서 "실행" 기능을 사용할 수 있습니다.http://docs.angularjs.org/api/angular.Module
이 코드는 인젝터 생성 후 실행되므로 사용하려는 서비스를 이용할 수 있습니다.
언급URL : https://stackoverflow.com/questions/19276095/execute-code-at-startup-of-angular-application
반응형
'programing' 카테고리의 다른 글
워드프레스 검색 기능으로 게시물만 검색 (0) | 2023.03.31 |
---|---|
필수 필드의 ngMessage를 더티 또는 폼 전송 시에만 표시하려면 어떻게 해야 합니까? (0) | 2023.03.31 |
Spring Security에서 권장되지 않는 Authorization Server를 대체할 수 있는 것은 무엇입니까? (0) | 2023.03.15 |
골랑에서 CORS를 유효하게 하다 (0) | 2023.03.15 |
Woocommerce 3의 판매 배지에 할인율을 표시합니다. (0) | 2023.03.15 |