rau*_*o21 77 angularjs angularjs-module
我试图用其他常量定义常量,但似乎无法完成,因为当需要的常量取决于它时,初始常量还没有准备好.我想确定这根本不可能.
目前我有这样的常量:
angular.module('mainApp.config', [])
.constant('RESOURCE_USERS_DOMAIN', 'http://127.0.0.1:8008')
.constant('RESOURCE_USERS_API', 'http://127.0.0.1:8008/users')
// Specific routes for API
.constant('API_BASIC_INFORMATION', RESOURCE_USERS_API + '/api/info')
.constant('API_SOCIAL_NETWORKS', RESOURCE_USERS_API + '/api/social')
;
Run Code Online (Sandbox Code Playgroud)
第二个两个常数是我想要完成的
Lin*_*iel 147
一个简单的方法是这样的:
var myApp = angular.module("exampleApp",[]);
myApp.constant('RESOURCES', (function() {
// Define your variable
var resource = 'http://127.0.0.1:8008';
// Use the variable in your constants
return {
USERS_DOMAIN: resource,
USERS_API: resource + '/users',
BASIC_INFO: resource + '/api/info'
}
})());
Run Code Online (Sandbox Code Playgroud)
并使用这样的常量:
myApp.controller("ExampleCtrl", function(RESOURCES){
$scope.domain = RESOURCES.USERS_DOMAIN;
});
Run Code Online (Sandbox Code Playgroud)
致谢:链接
lao*_*lao 45
定义控制器,服务和其他之间的依赖关系的角度方式是依赖注入(DI).因此,如果你有一个依赖于服务B的控制器A,你就必须像这样创建它.
var myApp = angular.module("exampleApp",[]);
myApp.controller("aCtrl", function(serviceB){
//Controller functionally here
});
Run Code Online (Sandbox Code Playgroud)
请参阅,angular将检查serviceB依赖项并查找使用该名称创建的服务.如果您不创建一个,您将收到错误.
所以,如果你想创建一个依赖于常数B的常数A,你需要告诉角度A取决于B.但常量不能有依赖性.常量可以返回一个函数,但DI不适用于常量.检查这个小提琴,这样你就可以看到DI的工作方式.
所以回答你的问题,你不能用其他常量定义常量.
但你可以这样做:
angular.module('projectApp', [])
.constant('domain','http://somedomain.com')
.constant('api','/some/api/info')
.service('urls',function(domain,api){ this.apiUrl = domain+api;})
.controller('mainCtrl',function($scope,urls) {
$scope.url = urls.apiUrl;
});
Run Code Online (Sandbox Code Playgroud)
检查这个小提琴看它是否有效:
如果您想了解有关DI的更多信息,请查看此文章.
我希望这可以回答你的问题.
Bet*_*aba 12
我这样做:
var constants = angular.module('constants', []);
constants.factory("Independent", [function() {
return {
C1: 42
}
}]);
constants.factory('Constants', ["Independent", function(I) {
return {
ANSWER_TO_LIFE: I.C1
}
}]);
Run Code Online (Sandbox Code Playgroud)
只要您不需要访问提供程序中的常量,这应该可以正常工作:
.constant('HOST', 'localhost')
.factory('URL', function(HOST) { return "http://" + HOST })
Run Code Online (Sandbox Code Playgroud)
如果您需要访问提供程序中的常量,那么我猜您还需要做更多的工作:
.constants('HOST', 'localhost')
.provider('DOMAIN', function(HOST) {
var domain = "http://" + HOST;
this.value = function() { return domain };
this.$get = this.value;
})
.provider("anyOtherProvider", function(DOMAINPovider) {
var domain = DOMAINProvider.value();
};
.factory("anyOtherService", function(DOMAIN) {
})
Run Code Online (Sandbox Code Playgroud)