简体   繁体   English

在控制器和数据对象之间同步数据

[英]Sync data between controller and dataobject

I've got an angular controller (TimeCtrl) and a factory (DataService) that manages the data across some other controllers. 我有一个角度控制器(TimeCtrl)和一个工厂(DataService),该工厂管理其他一些控制器中的数据。

In TimeCtrl there are variables like $scope.dateFrom and $scope.dateTo. 在TimeCtrl中,有$ scope.dateFrom和$ scope.dateTo这样的变量。 I want to make them share one memory space with the corresponding variables in the DataService (wacht.dateFrom and wacht.dateTo). 我想让它们与DataService中的相应变量(wacht.dateFrom和wacht.dateTo)共享一个内存空间。

I don't want to have multiple watcher, which look for changes in the DateFrom Input to change it also in the DataService. 我不想有多个观察者,这些观察者在DateFrom输入中查找更改以在DataService中也对其进行更改。

In short: A var should share it's value with another, without a sync func. 简而言之:变量应与另一个变量共享其值,而无需使用同步功能。

Is there a solution? 有解决方案吗?

Things like

$scope.dateTo = DataService.getWacht().dateTo = ''; 

in the TimeCtrl don't work like expected. 在TimeCtrl中无法正常工作。

Thanks for helping. 感谢您的帮助。

It is quite simple if you use object and assign it as property on controller and factory instance. 如果使用对象并将其分配为控制器和工厂实例的属性,则非常简单。

You can do it like this: 您可以这样做:

angular
    .module('app', []);

angular
    .module('app')
  .controller('Example', function (exFactory) {
    this.obj = exFactory.obj;
  });

angular
    .module('app')
  .factory('exFactory', function () {
    return {
        obj: {
        x: 0
      }
    };
  });

For full example look at this fiddle: https://jsfiddle.net/rnvLerqj/ 有关完整的示例,请查看此提琴: https : //jsfiddle.net/rnvLerqj/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM