Development Tip

AngularJS-컨트롤러에서 모듈 상수 가져 오기

yourdevel 2020. 10. 31. 10:11
반응형

AngularJS-컨트롤러에서 모듈 상수 가져 오기


내 앱에 대한 일부 설정을 저장하기 위해 myApp.config 모듈을 빌드하려고하는데 config.js 파일을 작성했습니다.

angular.module('myApp.config', [])
    .constant('APP_NAME','My Angular App!')
    .constant('APP_VERSION','0.3');

내 app.js (angular-seed)에 추가했습니다.

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
})

SimplGy의 솔루션은 '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...
});

angularJs 상수에 대한 전체 기사를 여기 에서 참조 하십시오.

참고URL : https://stackoverflow.com/questions/17383611/angularjs-getting-module-constants-from-a-controller

반응형