AngularJS:如何在控制器之间传递变量? [英] AngularJS: How can I pass variables between controllers?
问题描述
我有两个 Angular 控制器:
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
}
我不能在 Ctrl2
中使用 Ctrl1
因为它是未定义的.但是,如果我尝试像这样传递它......
I can't use Ctrl1
inside Ctrl2
because it is undefined. However if I try to pass it in like so…
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?
在做
Ctrl2.prototype = new Ctrl1();
也失败了.
注意:这些控制器没有相互嵌套.
NOTE: These controllers are not nested inside each other.
推荐答案
跨多个控制器共享变量的一种方法是 创建一个服务并将它注入到任何你想使用它的控制器中.
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.
简单服务示例:
angular.module('myApp', [])
.service('sharedProperties', function () {
var property = 'First';
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
});
在控制器中使用服务:
function Ctrl2($scope, sharedProperties) {
$scope.prop2 = "Second";
$scope.both = sharedProperties.getProperty() + $scope.prop2;
}
这在本博客(第 2 课尤其是).
This is described very nicely in this blog (Lesson 2 and on in particular).
我发现,如果您想跨多个控制器绑定到这些属性,最好绑定到对象的属性而不是原始类型(布尔值、字符串、数字)以保留绑定引用.
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.
示例:var property = { Property1: 'First' };
而不是 var property = 'First';
.
更新:(希望)让事情更清楚这里有一个小提琴a> 显示以下示例:
UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of:
- 绑定到共享值的静态副本(在 myController1 中)
- 绑定到原语(字符串)
- 绑定到对象的属性(保存到作用域变量)
- 绑定到返回原始(字符串)的函数
- 绑定到对象的属性
- 双向绑定对象的属性
这篇关于AngularJS:如何在控制器之间传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!