如何在控制器之间传递变量?

时间:2022-09-23 22:52:40

I have two Angular controllers:

我有两个角控制器

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
}

I can't use Ctrl1 inside Ctrl2 because it is undefined. However if I try to pass it in like so…

我不能在ctrl - 2中使用ctrl - l1,因为它没有定义。但是如果我试着像这样传递它……

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

I get an error. Does anyone know how to do this?

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

Doing

Ctrl2.prototype = new Ctrl1();

Also fails.

也失败了。

NOTE: These controllers are not nested inside each other.

注意:这些控制器不是相互嵌套的。

15 个解决方案

#1


493  

One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.

跨多个控制器共享变量的一种方法是创建一个服务并将其注入任何您想要使用它的控制器。

Simple service example:

简单服务的例子:

angular.module('myApp', [])
    .service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

Using the service in a controller:

在控制器中使用服务:

function Ctrl2($scope, sharedProperties) {
    $scope.prop2 = "Second";
    $scope.both = sharedProperties.getProperty() + $scope.prop2;
}

This is described very nicely in this blog (Lesson 2 and on in particular).

这在这篇博客(第2课,尤其是)中得到了很好的描述。

I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference.

我发现,如果您想跨多个控制器绑定到这些属性,那么如果您绑定到对象的属性而不是原始类型(布尔型、字符串型、数字型)以保留绑定引用,效果会更好。

Example: var property = { Property1: 'First' }; instead of var property = 'First';.

示例:var属性= {Property1: 'First'};而不是var属性= 'First';。


UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of:

更新:(希望)让事情更清楚,这里有一个小提琴展示了一个例子:

  • Binding to static copies of the shared value (in myController1)
    • Binding to a primitive (string)
    • 绑定到原语(字符串)
    • Binding to an object's property (saved to a scope variable)
    • 绑定到对象的属性(保存到范围变量)
  • 绑定到共享值(在myController1中)的静态副本,绑定到绑定到对象属性(保存到范围变量)的原语(字符串)
  • Binding to shared values that update the UI as the values are updated (in myController2)
    • Binding to a function that returns a primitive (string)
    • 绑定到返回原语(字符串)的函数
    • Binding to the object's property
    • 绑定到对象的属性
    • Two way binding to an object's property
    • 两路绑定到对象的属性
  • 绑定到在更新值(myController2中)时更新UI的共享值,绑定到返回对象属性的原语(字符串)绑定的函数,双向绑定对象的属性

#2


42  

I like to illustrate simple things by simple examples :)

我喜欢用简单的例子来说明简单的事情:

Here is a very simple Service example:

这里有一个非常简单的服务示例:


angular.module('toDo',[])

.service('dataService', function() {

  // private variable
  var _dataObj = {};

  // public API
  this.dataObj = _dataObj;
})

.controller('One', function($scope, dataService) {
  $scope.data = dataService.dataObj;
})

.controller('Two', function($scope, dataService) {
  $scope.data = dataService.dataObj;
});

And here the jsbin

这里的jsbin

And here is a very simple Factory example:

这里有一个非常简单的工厂例子:


angular.module('toDo',[])

.factory('dataService', function() {

  // private variable
  var _dataObj = {};

  // public API
  return {
    dataObj: _dataObj
  };
})

.controller('One', function($scope, dataService) {
  $scope.data = dataService.dataObj;
})

.controller('Two', function($scope, dataService) {
  $scope.data = dataService.dataObj;
});

And here the jsbin

这里的jsbin


If that is too simple, here is a more sophisticated example

如果这太简单,这里有一个更复杂的例子

Also see the answer here for related best practices comments

有关最佳实践的相关评论,请参见这里的答案

#3


25  

--- I know this answer is not for this question, but I want people who reads this question and want to handle Services such as Factories to avoid trouble doing this ----

---我知道这个答案不是针对这个问题的,但我希望读到这个问题并希望处理工厂等服务的人避免这样做的麻烦

For this you will need to use a Service or a Factory.

为此,您需要使用服务或工厂。

The services are the BEST PRACTICE to share data between not nested controllers.

服务是在不嵌套的控制器之间共享数据的最佳实践。

A very very good annotation on this topic about data sharing is how to declare objects. I was unlucky because I fell in a AngularJS trap before I read about it, and I was very frustrated. So let me help you avoid this trouble.

关于数据共享的一个非常好的注解是如何声明对象。我很不幸,因为在我读到这个故事之前,我掉进了一个盎格鲁人的陷阱,我非常沮丧。我来帮你避免麻烦。

I read from the "ng-book: The complete book on AngularJS" that AngularJS ng-models that are created in controllers as bare-data are WRONG!

我从“ng-book:关于AngularJS的完整的书”中读到,AngularJS的ng模型是在控制器中创建的,因为bare-data是错误的!

A $scope element should be created like this:

应该创建一个$scope元素,如下所示:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // best practice, always use a model
  $scope.someModel = {
    someValue: 'hello computer'
  });

And not like this:

而不是像这样:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // anti-pattern, bare value
  $scope.someBareValue = 'hello computer';
  };
});

This is because it is recomended(BEST PRACTICE) for the DOM(html document) to contain the calls as

这是因为需要为DOM(html文档)返回(最佳实践)以包含调用as

<div ng-model="someModel.someValue"></div>  //NOTICE THE DOT.

This is very helpful for nested controllers if you want your child controller to be able to change an object from the parent controller....

嵌套控制器来说,这是非常有用的,如果你想让你的孩子控制器能够改变一个对象的父控制器....

But in your case you don't want nested scopes, but there is a similar aspect to get objects from services to the controllers.

但是在您的情况下,您不需要嵌套的作用域,但是有一个类似的方面,可以从服务获取对象到控制器。

Lets say you have your service 'Factory' and in the return space there is an objectA that contains objectB that contains objectC.

假设您有您的服务“工厂”,在返回空间中有一个objectA,它包含了包含objectC的objectB。

If from your controller you want to GET the objectC into your scope, is a mistake to say:

如果您希望从控制器将objectC放到您的范围内,那么说:

$scope.neededObjectInController = Factory.objectA.objectB.objectC;

That wont work... Instead use only one dot.

不工作…只用一个点。

$scope.neededObjectInController = Factory.ObjectA;

Then, in the DOM you can call objectC from objectA. This is a best practice related to factories, and most important, it will help to avoid unexpected and non-catchable errors.

然后,在DOM中可以从objectA调用objectC。这是与工厂相关的最佳实践,最重要的是,它将有助于避免意外的和不可捕获的错误。

#4


15  

Solution without creating Service, using $rootScope:

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

To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.

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

The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $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;
}]);

Using $rootScope in a template (Access properties with $root):

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

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

#5


7  

The sample above worked like a charm. I just did a modification just in case I need to manage multiple values. I hope this helps!

上面的样品很有魅力。我只是做了一个修改,以防需要管理多个值。我希望这可以帮助!

app.service('sharedProperties', function () {

    var hashtable = {};

    return {
        setValue: function (key, value) {
            hashtable[key] = value;
        },
        getValue: function (key) {
            return hashtable[key];
        }
    }
});

#6


5  

I tend to use values, happy for anyone to discuss why this is a bad idea..

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

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

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

Then inject the value as per a service.

然后按服务注入值。

Set in ctrl1:

在ctrl1设置:

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

and access from ctrl2:

从ctrl2和访问:

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

});

#7


3  

I'd like to contribute to this question by pointing out that the recommended way to share data between controllers, and even directives, is by using services (factories) as it has been already pointed out, but also I'd like to provide a working practical example of how to that should be done.

我想对这个问题指出的推荐方法之间共享数据控制器,甚至指令,通过使用服务(工厂)已经指出的那样,但是我也想工作提供一个实际的例子应该做的如何。

Here is the working plunker: http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=info

这里是工作柱塞:http://plnkr.co/edit/q1vdkjp2tpvqqjl1lf6m?

First, create your service, that will have your shared data:

首先,创建您的服务,它将拥有您的共享数据:

app.factory('SharedService', function() {
  return {
    sharedObject: {
      value: '',
      value2: ''
    }
  };
});

Then, simply inject it on your controllers and grab the shared data on your scope:

然后,只需将其注入控制器并获取范围内的共享数据:

app.controller('FirstCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

app.controller('SecondCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

app.controller('MainCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

You can also do that for your directives, it works the same way:

你也可以做你的指示,它的工作方式是一样的:

app.directive('myDirective',['SharedService', function(SharedService){
  return{
    restrict: 'E',
    link: function(scope){
      scope.model = SharedService.sharedObject;
    },
    template: '<div><input type="text" ng-model="model.value"/></div>'
  }
}]);

Hope this practical and clean answer can be helpful to someone.

希望这个既实用又干净的答案能对某些人有所帮助。

#8


3  

The following example shows how to pass variables between siblings controllers and take an action when the value changes.

下面的示例展示了如何在兄弟控制器之间传递变量,并在值更改时采取操作。

Use case example: you have a filter in a sidebar that changes the content of another view.

用例示例:在侧边栏中有一个过滤器,用于更改另一个视图的内容。

angular.module('myApp', [])

  .factory('MyService', function() {

    // private
    var value = 0;

    // public
    return {
      
      getValue: function() {
        return value;
      },
      
      setValue: function(val) {
        value = val;
      }
      
    };
  })
  
  .controller('Ctrl1', function($scope, $rootScope, MyService) {

    $scope.update = function() {
      MyService.setValue($scope.value);
      $rootScope.$broadcast('increment-value-event');
    };
  })
  
  .controller('Ctrl2', function($scope, MyService) {

    $scope.value = MyService.getValue();

    $scope.$on('increment-value-event', function() {    
      $scope.value = MyService.getValue();
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  
  <h3>Controller 1 Scope</h3>
  <div ng-controller="Ctrl1">
    <input type="text" ng-model="value"/>
    <button ng-click="update()">Update</button>
  </div>
  
  <hr>
  
  <h3>Controller 2 Scope</h3>
  <div ng-controller="Ctrl2">
    Value: {{ value }}
  </div>  

</div>

#9


2  

Couldn't you also make the property part of the scopes parent?

您也不能让作用域的属性部分成为父类吗?

$scope.$parent.property = somevalue;

I'm not saying it's right but it works.

我不是说这是对的,但它确实有效。

#10


2  

Ah, have a bit of this new stuff as another alternative. It's localstorage, and works where angular works. You're welcome. (But really, thank the guy)

啊,有一点新的东西作为另一种选择。它是localstorage,在有角的地方工作。你是受欢迎的。(真的,谢谢你)

https://github.com/gsklee/ngStorage

https://github.com/gsklee/ngStorage

Define your defaults:

定义你的默认值:

$scope.$storage = $localStorage.$default({
    prop1: 'First',
    prop2: 'Second'
});

Access the values:

访问的值:

$scope.prop1 = $localStorage.prop1;
$scope.prop2 = $localStorage.prop2;

Store the values

存储的值

$localStorage.prop1 = $scope.prop1;
$localStorage.prop2 = $scope.prop2;

Remember to inject ngStorage in your app and $localStorage in your controller.

记得在app中注入ngStorage,在控制器中注入$localStorage。

#11


2  

You could do that with services or factories. They are essentially the same apart for some core differences. I found this explanation on thinkster.io to be the easiest to follow. Simple, to the point and effective.

你可以用服务或工厂来做。它们在某些核心差异上本质上是相同的。我在thinkster网站上找到了这个解释。io是最容易遵循的。简单,直截了当,有效。

#12


1  

There are two ways to do this

有两种方法可以做到这一点

1) Use get/set service

1)使用获取/设置服务

2) $scope.$emit('key', {data: value}); //to set the value

2)美元范围。释放美元(“关键”,{数据:价值});/ /设置值

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

#13


1  

Second Approach :

第二种方法:

angular.module('myApp', [])
  .controller('Ctrl1', ['$scope',
    function($scope) {

    $scope.prop1 = "First";

    $scope.clickFunction = function() {
      $scope.$broadcast('update_Ctrl2_controller', $scope.prop1);
    };
   }
])
.controller('Ctrl2', ['$scope',
    function($scope) {
      $scope.prop2 = "Second";

        $scope.$on("update_Ctrl2_controller", function(event, prop) {
        $scope.prop = prop;

        $scope.both = prop + $scope.prop2; 
    });
  }
])

Html :

Html:

<div ng-controller="Ctrl2">
  <p>{{both}}</p>
</div>

<button ng-click="clickFunction()">Click</button>

For more details see plunker :

有关详细信息,请参见“柱塞”:

http://plnkr.co/edit/cKVsPcfs1A1Wwlud2jtO?p=preview

http://plnkr.co/edit/cKVsPcfs1A1Wwlud2jtO?p=preview

#14


0  

If you don't want to make service then you can do like this.

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

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

#15


-1  

Besides $rootScope and services, there is a clean and easy alternative solution to extend angular to add the shared data:

除了$rootScope和服务,还有一个干净简单的替代解决方案来扩展角度以添加共享数据:

in the controllers:

控制器:

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

This properties belong to 'angular' object, separated from the scopes, and can be shared in scopes and services.

这些属性属于“角度”对象,与作用域分离,可以在作用域和服务*享。

1 benefit of it that you don't have to inject the object: they are accessible anywhere immediately after your defination!

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

#1


493  

One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.

跨多个控制器共享变量的一种方法是创建一个服务并将其注入任何您想要使用它的控制器。

Simple service example:

简单服务的例子:

angular.module('myApp', [])
    .service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

Using the service in a controller:

在控制器中使用服务:

function Ctrl2($scope, sharedProperties) {
    $scope.prop2 = "Second";
    $scope.both = sharedProperties.getProperty() + $scope.prop2;
}

This is described very nicely in this blog (Lesson 2 and on in particular).

这在这篇博客(第2课,尤其是)中得到了很好的描述。

I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference.

我发现,如果您想跨多个控制器绑定到这些属性,那么如果您绑定到对象的属性而不是原始类型(布尔型、字符串型、数字型)以保留绑定引用,效果会更好。

Example: var property = { Property1: 'First' }; instead of var property = 'First';.

示例:var属性= {Property1: 'First'};而不是var属性= 'First';。


UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of:

更新:(希望)让事情更清楚,这里有一个小提琴展示了一个例子:

  • Binding to static copies of the shared value (in myController1)
    • Binding to a primitive (string)
    • 绑定到原语(字符串)
    • Binding to an object's property (saved to a scope variable)
    • 绑定到对象的属性(保存到范围变量)
  • 绑定到共享值(在myController1中)的静态副本,绑定到绑定到对象属性(保存到范围变量)的原语(字符串)
  • Binding to shared values that update the UI as the values are updated (in myController2)
    • Binding to a function that returns a primitive (string)
    • 绑定到返回原语(字符串)的函数
    • Binding to the object's property
    • 绑定到对象的属性
    • Two way binding to an object's property
    • 两路绑定到对象的属性
  • 绑定到在更新值(myController2中)时更新UI的共享值,绑定到返回对象属性的原语(字符串)绑定的函数,双向绑定对象的属性

#2


42  

I like to illustrate simple things by simple examples :)

我喜欢用简单的例子来说明简单的事情:

Here is a very simple Service example:

这里有一个非常简单的服务示例:


angular.module('toDo',[])

.service('dataService', function() {

  // private variable
  var _dataObj = {};

  // public API
  this.dataObj = _dataObj;
})

.controller('One', function($scope, dataService) {
  $scope.data = dataService.dataObj;
})

.controller('Two', function($scope, dataService) {
  $scope.data = dataService.dataObj;
});

And here the jsbin

这里的jsbin

And here is a very simple Factory example:

这里有一个非常简单的工厂例子:


angular.module('toDo',[])

.factory('dataService', function() {

  // private variable
  var _dataObj = {};

  // public API
  return {
    dataObj: _dataObj
  };
})

.controller('One', function($scope, dataService) {
  $scope.data = dataService.dataObj;
})

.controller('Two', function($scope, dataService) {
  $scope.data = dataService.dataObj;
});

And here the jsbin

这里的jsbin


If that is too simple, here is a more sophisticated example

如果这太简单,这里有一个更复杂的例子

Also see the answer here for related best practices comments

有关最佳实践的相关评论,请参见这里的答案

#3


25  

--- I know this answer is not for this question, but I want people who reads this question and want to handle Services such as Factories to avoid trouble doing this ----

---我知道这个答案不是针对这个问题的,但我希望读到这个问题并希望处理工厂等服务的人避免这样做的麻烦

For this you will need to use a Service or a Factory.

为此,您需要使用服务或工厂。

The services are the BEST PRACTICE to share data between not nested controllers.

服务是在不嵌套的控制器之间共享数据的最佳实践。

A very very good annotation on this topic about data sharing is how to declare objects. I was unlucky because I fell in a AngularJS trap before I read about it, and I was very frustrated. So let me help you avoid this trouble.

关于数据共享的一个非常好的注解是如何声明对象。我很不幸,因为在我读到这个故事之前,我掉进了一个盎格鲁人的陷阱,我非常沮丧。我来帮你避免麻烦。

I read from the "ng-book: The complete book on AngularJS" that AngularJS ng-models that are created in controllers as bare-data are WRONG!

我从“ng-book:关于AngularJS的完整的书”中读到,AngularJS的ng模型是在控制器中创建的,因为bare-data是错误的!

A $scope element should be created like this:

应该创建一个$scope元素,如下所示:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // best practice, always use a model
  $scope.someModel = {
    someValue: 'hello computer'
  });

And not like this:

而不是像这样:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // anti-pattern, bare value
  $scope.someBareValue = 'hello computer';
  };
});

This is because it is recomended(BEST PRACTICE) for the DOM(html document) to contain the calls as

这是因为需要为DOM(html文档)返回(最佳实践)以包含调用as

<div ng-model="someModel.someValue"></div>  //NOTICE THE DOT.

This is very helpful for nested controllers if you want your child controller to be able to change an object from the parent controller....

嵌套控制器来说,这是非常有用的,如果你想让你的孩子控制器能够改变一个对象的父控制器....

But in your case you don't want nested scopes, but there is a similar aspect to get objects from services to the controllers.

但是在您的情况下,您不需要嵌套的作用域,但是有一个类似的方面,可以从服务获取对象到控制器。

Lets say you have your service 'Factory' and in the return space there is an objectA that contains objectB that contains objectC.

假设您有您的服务“工厂”,在返回空间中有一个objectA,它包含了包含objectC的objectB。

If from your controller you want to GET the objectC into your scope, is a mistake to say:

如果您希望从控制器将objectC放到您的范围内,那么说:

$scope.neededObjectInController = Factory.objectA.objectB.objectC;

That wont work... Instead use only one dot.

不工作…只用一个点。

$scope.neededObjectInController = Factory.ObjectA;

Then, in the DOM you can call objectC from objectA. This is a best practice related to factories, and most important, it will help to avoid unexpected and non-catchable errors.

然后,在DOM中可以从objectA调用objectC。这是与工厂相关的最佳实践,最重要的是,它将有助于避免意外的和不可捕获的错误。

#4


15  

Solution without creating Service, using $rootScope:

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

To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.

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

The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $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;
}]);

Using $rootScope in a template (Access properties with $root):

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

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

#5


7  

The sample above worked like a charm. I just did a modification just in case I need to manage multiple values. I hope this helps!

上面的样品很有魅力。我只是做了一个修改,以防需要管理多个值。我希望这可以帮助!

app.service('sharedProperties', function () {

    var hashtable = {};

    return {
        setValue: function (key, value) {
            hashtable[key] = value;
        },
        getValue: function (key) {
            return hashtable[key];
        }
    }
});

#6


5  

I tend to use values, happy for anyone to discuss why this is a bad idea..

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

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

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

Then inject the value as per a service.

然后按服务注入值。

Set in ctrl1:

在ctrl1设置:

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

and access from ctrl2:

从ctrl2和访问:

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

});

#7


3  

I'd like to contribute to this question by pointing out that the recommended way to share data between controllers, and even directives, is by using services (factories) as it has been already pointed out, but also I'd like to provide a working practical example of how to that should be done.

我想对这个问题指出的推荐方法之间共享数据控制器,甚至指令,通过使用服务(工厂)已经指出的那样,但是我也想工作提供一个实际的例子应该做的如何。

Here is the working plunker: http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=info

这里是工作柱塞:http://plnkr.co/edit/q1vdkjp2tpvqqjl1lf6m?

First, create your service, that will have your shared data:

首先,创建您的服务,它将拥有您的共享数据:

app.factory('SharedService', function() {
  return {
    sharedObject: {
      value: '',
      value2: ''
    }
  };
});

Then, simply inject it on your controllers and grab the shared data on your scope:

然后,只需将其注入控制器并获取范围内的共享数据:

app.controller('FirstCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

app.controller('SecondCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

app.controller('MainCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

You can also do that for your directives, it works the same way:

你也可以做你的指示,它的工作方式是一样的:

app.directive('myDirective',['SharedService', function(SharedService){
  return{
    restrict: 'E',
    link: function(scope){
      scope.model = SharedService.sharedObject;
    },
    template: '<div><input type="text" ng-model="model.value"/></div>'
  }
}]);

Hope this practical and clean answer can be helpful to someone.

希望这个既实用又干净的答案能对某些人有所帮助。

#8


3  

The following example shows how to pass variables between siblings controllers and take an action when the value changes.

下面的示例展示了如何在兄弟控制器之间传递变量,并在值更改时采取操作。

Use case example: you have a filter in a sidebar that changes the content of another view.

用例示例:在侧边栏中有一个过滤器,用于更改另一个视图的内容。

angular.module('myApp', [])

  .factory('MyService', function() {

    // private
    var value = 0;

    // public
    return {
      
      getValue: function() {
        return value;
      },
      
      setValue: function(val) {
        value = val;
      }
      
    };
  })
  
  .controller('Ctrl1', function($scope, $rootScope, MyService) {

    $scope.update = function() {
      MyService.setValue($scope.value);
      $rootScope.$broadcast('increment-value-event');
    };
  })
  
  .controller('Ctrl2', function($scope, MyService) {

    $scope.value = MyService.getValue();

    $scope.$on('increment-value-event', function() {    
      $scope.value = MyService.getValue();
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  
  <h3>Controller 1 Scope</h3>
  <div ng-controller="Ctrl1">
    <input type="text" ng-model="value"/>
    <button ng-click="update()">Update</button>
  </div>
  
  <hr>
  
  <h3>Controller 2 Scope</h3>
  <div ng-controller="Ctrl2">
    Value: {{ value }}
  </div>  

</div>

#9


2  

Couldn't you also make the property part of the scopes parent?

您也不能让作用域的属性部分成为父类吗?

$scope.$parent.property = somevalue;

I'm not saying it's right but it works.

我不是说这是对的,但它确实有效。

#10


2  

Ah, have a bit of this new stuff as another alternative. It's localstorage, and works where angular works. You're welcome. (But really, thank the guy)

啊,有一点新的东西作为另一种选择。它是localstorage,在有角的地方工作。你是受欢迎的。(真的,谢谢你)

https://github.com/gsklee/ngStorage

https://github.com/gsklee/ngStorage

Define your defaults:

定义你的默认值:

$scope.$storage = $localStorage.$default({
    prop1: 'First',
    prop2: 'Second'
});

Access the values:

访问的值:

$scope.prop1 = $localStorage.prop1;
$scope.prop2 = $localStorage.prop2;

Store the values

存储的值

$localStorage.prop1 = $scope.prop1;
$localStorage.prop2 = $scope.prop2;

Remember to inject ngStorage in your app and $localStorage in your controller.

记得在app中注入ngStorage,在控制器中注入$localStorage。

#11


2  

You could do that with services or factories. They are essentially the same apart for some core differences. I found this explanation on thinkster.io to be the easiest to follow. Simple, to the point and effective.

你可以用服务或工厂来做。它们在某些核心差异上本质上是相同的。我在thinkster网站上找到了这个解释。io是最容易遵循的。简单,直截了当,有效。

#12


1  

There are two ways to do this

有两种方法可以做到这一点

1) Use get/set service

1)使用获取/设置服务

2) $scope.$emit('key', {data: value}); //to set the value

2)美元范围。释放美元(“关键”,{数据:价值});/ /设置值

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

#13


1  

Second Approach :

第二种方法:

angular.module('myApp', [])
  .controller('Ctrl1', ['$scope',
    function($scope) {

    $scope.prop1 = "First";

    $scope.clickFunction = function() {
      $scope.$broadcast('update_Ctrl2_controller', $scope.prop1);
    };
   }
])
.controller('Ctrl2', ['$scope',
    function($scope) {
      $scope.prop2 = "Second";

        $scope.$on("update_Ctrl2_controller", function(event, prop) {
        $scope.prop = prop;

        $scope.both = prop + $scope.prop2; 
    });
  }
])

Html :

Html:

<div ng-controller="Ctrl2">
  <p>{{both}}</p>
</div>

<button ng-click="clickFunction()">Click</button>

For more details see plunker :

有关详细信息,请参见“柱塞”:

http://plnkr.co/edit/cKVsPcfs1A1Wwlud2jtO?p=preview

http://plnkr.co/edit/cKVsPcfs1A1Wwlud2jtO?p=preview

#14


0  

If you don't want to make service then you can do like this.

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

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

#15


-1  

Besides $rootScope and services, there is a clean and easy alternative solution to extend angular to add the shared data:

除了$rootScope和服务,还有一个干净简单的替代解决方案来扩展角度以添加共享数据:

in the controllers:

控制器:

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

This properties belong to 'angular' object, separated from the scopes, and can be shared in scopes and services.

这些属性属于“角度”对象,与作用域分离,可以在作用域和服务*享。

1 benefit of it that you don't have to inject the object: they are accessible anywhere immediately after your defination!

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