Saturday, 15 June 2013

javascript - AngularJS: $watch other service in a service -



javascript - AngularJS: $watch other service in a service -

i have service, , want watch info of other service (so event triggered, when info changed).

// gets info json file , saves in this.data myservice.service('myservice', ['$http', function($http) { this.data = {}; // returned $watch this.loaddata = function( ){ $http.get('http://localhost/data.json'). success(function(json, status, headers, config) { this.data = json; // wont returned $watch }); } }]);

now, different services, phone call load function , have $watch event:

// load info myservice.loaddata( ); // $watch effort #1 $rootscope.$watch('myservice.data', function(data){ console.log(myservice.data); }, true); // $watch effort #2 $rootscope.$watch(function(){ homecoming myservice.data; }, function(newval, oldval){ console.log(newval); });

both $watch attempts show me in firebug-console: {} (from this.data = {};) this.data = json; wont displayed.

what did wrong? there way event when info changed?

thank much.

you setting data wrong object because context (this) going different within success callback. simple prepare referent service context variable, var self = this:

this.loaddata = function() { var self = this; $http.get('http://localhost/data.json'). success(function(json, status, headers, config) { self.data = json; }); }

javascript angularjs

No comments:

Post a Comment