0

index.html

      <body >
      <p ng-controller="MainCtrl as mv">Hello {{mv.name}}!</p>
      <hr>
      <div ng-controller="MainCtrl2 as mv">
      <input type="text" ng-model="name">
      <button ng-click="mv.setN(name)">submit</button><br>
      Hello {{name}}<br>
      Hello {{mv.name}}!

   </div>
  </body> 

app.js :

var app = angular.module('plunker', []);

app.service('myService', function() {
var my = this;
my.name = "original";
});

app.controller('MainCtrl', function(myService) {
var mv = this;
mv.name = myService.name;
});

app.controller('MainCtrl2', function(myService) {
var mv = this;
mv.name = myService.name;

mv.setN = function(a) {
  myService.name = a;

  };
});

why isn't the service able to establish communication between controllers ?I have seen a similar example of factory which is working for communication. my plunk: http://plnkr.co/edit/L5uRHPQiXqQV6K7twHul?p=preview

4
  • its a bit more complex then that to get two controllers to communicate together , maybe go through a tutorial that is explaining just that Commented Jul 21, 2015 at 23:35
  • if I remember correctly you have to pass the controllers to the service , and the controllers I think have to have public facing functions that are designed to return responses Commented Jul 21, 2015 at 23:37
  • it would if you maintained object references and not convert to primitves plnkr.co/edit/C1yoKjKJMXkFIvswUGUo?p=preview Commented Jul 21, 2015 at 23:41
  • golden rule...always have a dot in ng-model Commented Jul 21, 2015 at 23:42

1 Answer 1

2

Check the working demo: http://plnkr.co/edit/cTqJImTLdDwPzGsKxN6W?p=preview

Always use Object to share models. Your service should be changed to:

app.service('myService',function(){
  var my=this;
  my.n = {
    name: 'paven'
  };
  my.setN=function(a){
      my.n.name=a;
      console.log("name change to "+my.n.name);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.