[英]Angularjs: a factory to share data between controllers
I have an angular.js app with multiple views, and I need to preserve status among view change. 我有一个具有多个视图的angular.js应用程序,我需要保留视图更改之间的状态。
So I use a very simple factory to share data. 因此,我使用一个非常简单的工厂来共享数据。
And, in the controllers, I use the factory name to use my data, instead of "$scope": 并且,在控制器中,我使用工厂名称来使用我的数据,而不是“ $ scope”:
app.factory('share', function() {
return {};
}
app.controller('FirstCtrl', function ($scope, share) {
share.obj1['a'] = 'ABC';
});
app.controller('SecondCtrl', function ($scope, share) {
share.obj1['b'] = 'DEF';
if (share.obj1['a'] === 'ABC') {
...
}
});
And, my simplified html view is like this: 而且,我的简化html视图如下所示:
...
<div ng-repeat="(key, item) in obj1">
{{item}}
</div>
...
This of course doesn't work, because ng-* directives in views only have access to $scope... 这当然是行不通的,因为视图中的ng- *指令只能访问$ scope ...
Is it possible to keep my data in sync with share factory using $scope? 是否可以使用$ scope使数据与共享工厂保持同步?
You can just do $scope.share = share
at the end of each controller and of course modify the view: 您只需在每个控制器的末尾执行
$scope.share = share
,当然可以修改视图:
<div ng-repeat="(key, item) in share.obj1">
Alternatively, and if the structure of share
is NOT going to change (there is always an obj1
), you could do angular.extend($scope, share)
. 另外,如果
share
的结构不会改变(总是有obj1
),则可以执行angular.extend($scope, share)
。 This is dangerous if share
gets new properties, these will not be seen by the scope, until a new controller is created. 如果
share
获得新属性,这将很危险 ,在创建新控制器之前,示波器将看不到这些新属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.