angularjs - Why is my angular service value not updating my scope? -
i have this simple jsfiddle demonstrates thought dynamic service value monitored controller injected. here angular code:
var app = angular.module("application", []); app.service("valuesetter", function(){ = this; this.servicevalue = {count: 1}; this.updatevalue = function(){ that.servicevalue.count = that.servicevalue.count + 1; console.log(that.servicevalue); }; }); app.controller("appcontroller", function($scope, valuesetter){ $scope.scopevalue = valuesetter.servicevalue.count; $scope.update = function(){ valuesetter.updatevalue(); }; });
and html simple:
<div ng-app="application" ng-controller="appcontroller"> scope value is: {{scopevalue}}<br /><br /> <input type="button" value="update" ng-click="update()" /> </div>
if watch console, can see service value increment, incremented value not reflected in controller scope. misunderstanding how should working?
you can't bind service variable that, can bind service function. add together getter service:
this.getvalue = function(){ homecoming that.servicevalue; }
assign scopevalue
in controller getter:
$scope.scopevalue = valuesetter.getvalue;
bind this:
scope value is: {{scopevalue()}}
edit you can assign valuesetter
service $scope
variable in controller:
$scope.valuesetter = valuesetter;
and bind this:
service value is: {{valuesetter.servicevalue}}
demo
edit 2you can alter this.servicevalue
in service object, this:
this.servicevalue = {value: 1}; this.updatevalue = function(){ that.servicevalue.value = that.servicevalue.value + 1; console.log(that.servicevalue.value); };
in controller, assign scopevalue
this:
$scope.scopevalue = valuesetter.servicevalue;
and bind this:
scope value is: {{scopevalue.value}}
demo
the point if property in service primitive (essentially string, number, or boolean), when assign scope variable, you're making re-create of value, , has no link service. if service property object, when assign scope variable, you're copying reference service property, gives binding looking for.
angularjs
No comments:
Post a Comment