puppeteer701
puppeteer701

Reputation: 1285

Scope variable reference to service data AngularJS

I have a service with an object, and that object has a property value, and I set this to reference to a scope value of a controller. Why when I update scope value, services value is not updated, or vice versa????

 .service('Item', function () { return { value: 0 }}
 .ctrl('Ctrl', function ($scope, Item) { 
     $scope.value = Item.value;
     Item.value = 2;
 });

Upvotes: 1

Views: 1536

Answers (1)

Rohan Chandane
Rohan Chandane

Reputation: 367

Try this -

app.service('Item', function(){
    this.value = 0; // instead of value return { value: 0 }
});

app.controller('ACtrl', function ($scope, Item) { 
   console.log('Item', Item);

   $scope.value = Item.value;
   console.log('$scope.value', $scope.value);

   Item.value = 2;
   console.log('Item', Item);
});

Here is the output of above code -

Item Constructor {value: 0} 
$scope.value 0 
Item Constructor {value: 2} 

Here, Plnker code

Upvotes: 1

Related Questions