如何在AngularJS中创建一个具有控制器间可共享属性的对象

How to create a object with properties that are sharable among controllers in AngularJS?

本文关键字:控制器 共享 对象 属性 一个 AngularJS 创建      更新时间:2023-09-26

这是如何在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中创建一个具有控制器之间可共享属性的对象?这样,我只需要注入一个对象,而不是许多常量。这能在Angularjs中实现吗?谢谢。

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);
  ...
}]);

您可以使用factory:

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

您可以通过多种方式在不同的控制器之间共享对象或变量-

    使用工厂
  1. 使用服务
  2. 广播或发射

如果你的要求只是在多个控制器之间共享变量,你可以使用服务来实现。

创建一个服务如下-这里的名称是sharedService。您可以使用自己的服务名称。然后使用'this'关键字定义/声明变量(你想要多少就有多少)。

    var app = angular.module('app', []);
    app.service('sharedService', function ($rootScope) {
    this.globalvar1 = "my global variable1";
    this.globalvar2="";
    });

在你的控制器中注入service,然后像下面这样访问service变量

 app.controller('myController', ['$scope', 'sharedService',
    function ($scope,sharedService) {
    var myGlobalVariable=sharedService.globalvar1;
    sharedService.globalvar1="my global variable value changed from controller";
    }]);

你可以在所有的控制器中使用服务变量但是你必须在控制器中注入服务名