programing

각도 응용 프로그램 시작 시 코드 실행

coolbiz 2023. 3. 15. 23:23
반응형

각도 응용 프로그램 시작 시 코드 실행

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

반응형