我有两个Angular控制器:

function Ctrl1($scope) {
    $scope.prop1 = "First";
}

function Ctrl2($scope) {
    $scope.prop2 = "Second";
    $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}

我不能在Ctrl2中使用Ctrl1,因为它是未定义的。然而,如果我试图像这样传递它。

function Ctrl2($scope, Ctrl1) {
    $scope.prop2 = "Second";
    $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}

我得到一个错误。有人知道怎么做吗?

Ctrl2.prototype = new Ctrl1();

也失败了。

注意:这些控制器彼此之间不是嵌套的。


当前回答

如果你不想做服务,你可以这样做。

var scope = angular.element("#another ctrl scope element id.").scope();
scope.plean_assign = some_value;

其他回答

除了$rootScope和services,还有一个干净简单的解决方案来扩展angular来添加共享数据:

在控制器中:

angular.sharedProperties = angular.sharedProperties 
    || angular.extend(the-properties-objects);

该属性属于'angular'对象,与作用域分离,可以在作用域和服务中共享。

它的一个好处是你不需要注入对象:它们可以在你定义后的任何地方立即访问!

如果你不想做服务,你可以这样做。

var scope = angular.element("#another ctrl scope element id.").scope();
scope.plean_assign = some_value;

我倾向于使用价值观,乐意任何人讨论为什么这是一个坏主意。

var myApp = angular.module('myApp', []);

myApp.value('sharedProperties', {}); //set to empty object - 

然后按服务注入值。

在ctrl1中设置:

myApp.controller('ctrl1', function DemoController(sharedProperties) {
  sharedProperties.carModel = "Galaxy";
  sharedProperties.carMake = "Ford";
});

从ctrl2访问:

myApp.controller('ctrl2', function DemoController(sharedProperties) {
  this.car = sharedProperties.carModel + sharedProperties.carMake; 

});

有两种方法

1)使用get/set服务

2) 美元的范围。$emit('key', {data: value});//设置该值

 $rootScope.$on('key', function (event, data) {}); // to get the value

不创建服务的解决方案,使用$rootScope:

要跨应用控制器共享属性,你可以使用Angular $rootScope。这是共享数据的另一种选择,让人们知道它。

在控制器之间共享一些功能的首选方式是服务,读取或更改全局属性可以使用$rootscope。

var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = true;
}]);

app.controller('Ctrl2', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = false;
}]);

在模板中使用$rootScope(使用$root访问属性):

<div ng-controller="Ctrl1">
    <div class="banner" ng-show="$root.showBanner"> </div>
</div>