繁体   English   中英

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

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

这是有关如何创建要在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);
  ...
}]);

您可以为此使用工厂:

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. 使用服务

  3. 广播或发射

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

如下创建服务-这里的名称是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";
    }]);

您可以在所有控制器中使用服务变量,但必须在控制器中注入服务名称

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM