반응형
AngularJS - 컨트롤러에서 모듈 상수 가져오기
앱 설정을 저장하기 위해 myApp.config 모듈을 구축하려고 하는데 config.js 파일을 작성했습니다.
angular.module('myApp.config', [])
.constant('APP_NAME','My Angular App!')
.constant('APP_VERSION','0.3');
app.js(각선 시드)에 추가했습니다.
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'myApp.config']).
index.html 파일에 추가해 컨트롤러에 도입하는 방법을 찾고 있습니다.
angular.module('myApp.controllers', ['myApp.config'])
.controller('ListCtrl', ['$scope', 'myApp.config', function($scope, $config) {
$scope.printme = $config;
}])
하지만 난 이해한다:
알 수 없는 공급자: myApp.configProvider <- myApp.config
내가 뭔가 잘못하고 있는 것 같은데, 뭐 생각나는 거 없어?
그런 주입에 모듈명을 사용하는 것은 타당하지 않다고 생각합니다.이름으로만 상수를 주입할 수 있습니다.
angular.module('myApp.controllers', ['myApp.config'])
.controller('ListCtrl', ['$scope', 'APP_NAME', function($scope, appName) {
$scope.printme = appName;
}]);
가장 간단한 방법은 객체 리터럴을 사용하여 상수를 추가하는 것이라고 생각합니다.이는 복잡한 구성 개체를 지원하기 때문에 대부분의 애플리케이션 구성 사용 사례에 적합합니다.그constant스텝도 다른 프로바이더가 등록되기 전에 빨리 실행됩니다.
angular.module('myApp').constant('cfg', {
url: 'https://myapi.com/v1/',
httpTimeout: 5000
})
사용하기 위해서는 주사만 하면 됩니다.cfg:
angular.module('myApp').factory('user', function(cfg, $http){
// cfg and $http together at last
})
또한 SimplyGy의 솔루션은 'cfg' 객체가 일정하지만 해당 객체의 속성은 일정하지 않음을 의미합니다.즉, 다음과 같이 'cfg'를 재할당할 수 없습니다.
cfg = { randomProperty: randomValue };
다음과 같이 'cfg' 개체의 속성을 재할당할 수 있습니다.
cfg.url = 'BrandNewURL.com';
cfg.httpTimeout = 30;
이 예에서는 상수의 사용을 확인합니다.
angular
.module('abp001App', ['ngRoute'])
.constant("myConfig", {
"url": "http://localhost",
"port": "80"
})
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.controller('MainCtrl', function (myConfig) {
// Do something with myConfig...
});
언급URL : https://stackoverflow.com/questions/17383611/angularjs-getting-module-constants-from-a-controller
반응형
'programing' 카테고리의 다른 글
| $parse, $interpolate 및 $compile 서비스의 차이점은 무엇입니까? (0) | 2023.02.08 |
|---|---|
| JSON 로그 파일을 쓰는 형식을 선택하십시오. (0) | 2023.02.08 |
| JSON 입력 스트림을 해석하는 방법 (0) | 2023.02.08 |
| 인증된 XMLHttpRequest 후에 브라우저가 인가 헤더를 재사용하지 않는 이유는 무엇입니까? (0) | 2023.02.08 |
| 각도 감시 사이클 또는 다이제스트 사이클이 완료되면 함수를 호출하는 방법 (0) | 2023.02.08 |