Sync up JSON objects on the same page with various AngularJS controllers -
one page divided several sections , each section has own controller. json objects on sections related. after actions performed in 1 section, state of json object changed. change shall propagate other sections of page. 1 controller can access object, $scope.foo, in controller. have $scope.foo = ... after action of previous controller. code, however, doesn't sync data displayed in section.
also, have set of json objects not accessible in controller. , 1 object in controller 1 of objects. how sync them up? angularjs observer approach problem?
based on lux's suggestion, create service following:
angular.module('myapp.services') .service('fooservice', ['notificationcenter', function (notificationcenter) { "use strict"; var foo; function setfoo(f) { foo = f; } function getfoo() { return foo; } var facade = { getfoo: getfoo, setfoo: setfoo }; return facade;
}]);
and in controller of displaying foo data, have
// web service call fooservice.setfoo(response); $scope.currentfoo = fooservice.getfoo();
and in controller data altered, have
// after changing data , make put web service call retrieve updated data fooservice.setfoo(response);
the data first controller isn't updated.
do not use $rootscope
, if have need share data across controllers
, directives
, or services
use service. in angular, services
singletons, meaning same instance can shared across components, in turn means, if myservice.setmydata('foo')
in 1 place, can access updated data via myservice.getmydata()
in component.
Comments
Post a Comment