这是How to create this global constant to be shared among controllers in Angularjs?的后续问题。
所提供的答案允许控制器之间共享一个常量$webroot。
app = angular.module('myApp', []);
app.constant('$webroot', 'localhost/webroot/app');
app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
$scope.webroot = $webroot;
}]);但是,问题是,如果我有10个常量,那么所有10个常量都必须注入控制器。这使得控制器声明看起来又长又丑。如何创建一个属性在AngularJS中的控制器之间共享的对象?以这种方式,我只需要注入一个对象而不是许多常量。这能在安古拉杰完成吗?谢谢。
发布于 2014-03-28 10:52:00
var app = angular.module('app', []);
app.constant('config', {
prop1: 'val1',
prop2: 'val2',
...
});
app.controller('Ctrl', ['config', function(config) {
console.log(config.prop1);
console.log(config.prop2);
...
}]);发布于 2014-03-28 10:51:39
你可以用一家工厂做这个:
app = angular.module('myApp', []);
app.factory('MyGlobals', function() {
return {
globalOne: 12345,
globalTwo: 'Hey there',
globalThree: {foo: 'bar'},
globalFour: [1, 2, 3, 4],
isFoo: function () {
return (this.globalTwo == 'Foo' ? true : false);
}
}
});
app.controller('myController', ['$scope', 'MyGlobals', function($scope, MyGlobals) {
$scope.globalOne = MyGlobals.globalOne
[...]
if (MyGlobals.isFoo()) {
// Be creative
}
}]);发布于 2014-03-28 11:59:00
您可以在不同的控制器之间以多种方式共享对象或变量-
如果您的需求只是在多个控制器之间共享变量,则可以使用服务来实现这一点。
创建一个服务如下-这里的名字是sharedService。您可以使用自己的服务名称。然后使用“this”关键字定义/声明变量(如您所需)。
var app = angular.module('app', []);
app.service('sharedService', function ($rootScope) {
this.globalvar1 = "my global variable1";
this.globalvar2="";
});在控制器中注入服务,然后访问服务变量,如下所示
app.controller('myController', ['$scope', 'sharedService',
function ($scope,sharedService) {
var myGlobalVariable=sharedService.globalvar1;
sharedService.globalvar1="my global variable value changed from controller";
}]);您可以在所有控制器中使用服务变量,但必须在控制器中注入服务名称。
https://stackoverflow.com/questions/22710593
复制相似问题