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' };
(示例: var property = { Property1: 'First' };
)
instead of var property = 'First';
(而不是var property = '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)(绑定到共享值的静态副本(在myController1中))
- Binding to a primitive (string)(绑定到原语(字符串))
- Binding to an object's property (saved to a scope variable)(绑定到对象的属性(保存到范围变量))
- Binding to shared values that update the UI as the values are updated (in myController2)(绑定到在更新值时更新UI的共享值(在myController2中))
- Binding to a function that returns a primitive (string)(绑定到返回原语(字符串)的函数)
- Binding to the object's property(绑定到对象的属性)
- Two way binding to an object's property(双向绑定到对象的属性)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…