Skip to content Skip to sidebar Skip to footer

How Do $scope And This Techniques Differ In Terms Of Sharing Data Via Services?

If you're going to create new code, please don't change the original jsbins I am writing an app in angular 1. Right now I need to create a service I can inject in multiple controll

Solution 1:

Basically $scope and this are the same thing as you stated at your question.

When you retrieve ControllerAs(myController2 as cont2) in your template, everything(variables and functions) you want to access from template to controller must have a prefix of cont2.

And in your first jsbin, you have missed one prefix cont2 at calling cont2.setString(newValue) and it should be cont2.setString(cont2.newValue). else you can't pass what you have typed at the textbox.


UPD:

Normally if value lept at sharedService changed, we have to manually call service functions to get the newValue as answered by @Sumit Deshpande.

There is still another way that you can bind the same object instance to controller's varaible with the object instance kept in sharedService, but keep in mind that this way don't support filed of string type(unless you put the string filed in object filed too).

refer the below plunker.


Solution 2:

To reflect the data when change is happened in service there are 2 ways to do that -

  1. Use Publisher Subscriber mechanism to broadcast and listen when change occurred in service variable/object.
  2. Bind directly through service method to achieve the same.

Here is the sample code for 2# -

app.controller('myController1', function($timeout, sharedProperties) {
    var vm = this;
    vm.service = sharedProperties;
});

app.controller('myController2', function(sharedProperties) {        
    var vm = this;
    vm.service = sharedProperties;  
    vm.setString = function(newValue) 
    {   console.log(newValue);
        vm.objectValue.data = newValue;
        vm.service.setString(newValue);
    };
});

Html

<div ng-app="myApp">
    <div ng-controller="myController1 as cont1">
      <ul>
        <li><b>myController1</b> (values won't change)</li>
        <li>{{cont1.service.getString()}}</li>
        <li>{{cont1.service.getObject()}}</li>
      </ul>
    </div>    
    <div ng-controller="myController2 as cont2">
      <ul>
        <li><b>myController2</b> (values will change when Set Values is clicked or when 2-way binding textbox is modified)</li>
        <li>{{cont2.service.getString()}}</li>
        <li>{{cont2.service.getObject().data}}</li>
      </ul>
      <input type="text" ng-model="cont2.newValue"></input>
    <button ng-click="cont2.setString(cont2.newValue)">Set Values</button><br/>
    <input type="text" ng-model="cont2.objectValue.data"></input>2-way binding to objectValue
  </div>
  </div> 

Post a Comment for "How Do $scope And This Techniques Differ In Terms Of Sharing Data Via Services?"