[英]AngularJS data binding between service and controllers
I would like to have clarifications about data-binding with AngularJS. 我想澄清一下AngularJS的数据绑定。 I wish to have an array in service and share it with multiple controllers.
我希望有一个服务中的数组,并与多个控制器共享。
I would like , when a controller modify data in service, that the modification was take in account in others controllers et theirs html templates was update automatically. 我想,当控制器修改服务中的数据时,该修改已考虑到其他控制器中,并且他们的html模板是自动更新的。
Unfortunately, I succeed a little, but not with an angular manner because I use for this the Observer pattern or angular.copy.. 不幸的是,我取得了一些成功,但没有成功,因为我为此使用了Observer模式或angular.copy。
When I try with a pure angular way, it does not work. 当我尝试使用纯角度方式时,它不起作用。
Here an example of code: 这里是一个代码示例:
The service that contains datas to shared 包含要共享的数据的服务
app.factory( "MyService", [
function () {
myTableToShare = [];
return {
myTableToShared : myTableToShare,
};
}
] ); ]);
The controller that modify data of service 修改服务数据的控制器
app.controller( 'AddCtrl', [
'$scope', 'MyService', function ( $scope, MyService ) {
$scope.myService = MyService;
$scope.addElementToSharedTable = function( element ) {
$scope.myService.myTableToShare.push( element );
};
}] );
The controller that permit to print datas of table into template 允许将表格数据打印到模板中的控制器
app.controller( 'ReadCtrl', [
'$scope', 'MyService', function ( $scope, MyService ) {
$scope.myService = MyService;
}] );
**The template that print elements of table ** **打印表格元素的模板**
<div ng-controller="ReadCtrl">
<ul >
<li ng-repeat="element in myService.myTableToShare">
<span>{{element.id}} - {{element.name}}</span>
</li>
</ul> </div>
I have apply this method thanks to differents HOWTO. 由于有不同的HOWTO,所以我已经应用了此方法。 unfortunately these HOWTO did not use an array object but a String.
不幸的是,这些HOWTO没有使用数组对象,而是使用String。 Is it a path to follow?
这是一条可以走的路吗?
In waiting I apply the pattern observer et I notify events from controller to services but it seems to me that its not a good solution because it too verbose. 在等待时,我将模式观察器et应用于从控制器向服务通知事件,但是在我看来,这不是一个很好的解决方案,因为它太冗长了。
Thaks 解冻
如果控制器在同一模块“ app”中,请使用app.value(...)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.