javascript - AngularJS service does not return refence but value of object -
i find better use angularjs services communicate between 2 component rather using emit/broadcast techiques. have create simple userservice:
(function(){ angular.module('userservice') .factory('userservice', userservicefn); userservicefn.$inject = []; function userservicefn(){ var user = { islogged: false, info: '' }; return { setuser: setuser, getuser: getuser, clearuser: clearuser }; function setuser(info){ user.islogged = true; user.info = info; }; function getuser(){ return user; }; function clearuser(){ user.islogged = false; user.info = {}; }; } })();
then can inject service ever need no current login status var user = userservice.getuser();
, example toggle login button <button ng-hide="user.islogged">login</button>
great thing technique when ever use userservice.clearuser()
login button automatically shown because getuser()
passes reference of user object , ng-hide
binds changes in reference.
i created markerservice uses same techique there strange behavior. getcoords not return reference of coords value of coords.
(function(){ angular.module('app') .factory('markerservice', markerservicefn); markerservicefn.$inject = []; function markerservicefn(){ var coords = [ 56.936, 22.12 ]; return { setcoords: setcoords, getcoords: getcoords }; function setcoords(a){ console.log(coords); coords = a; console.log(coords); } function getcoords(){ return coords; } } })();
here working plunker. confuses me both service created in same way act differently. have spent 2 days finding reason of behavior, re-wrote code both services couple of times same issue.
in user service changing properties of object, not replacing object itself. because of reference in html not broken , see change.
in coordinates service replace object totally html still holds reference old object (which service doesn't reference).
you must change setcoords
to:
function setcoords(a){ coords[0] = a[0]; coords[1] = a[1]; }
Comments
Post a Comment