1

I have following html (sample)

<div ng-controller='ctrl-1'>
    <form>
        <input type='text' ng-model='name'/>
    </form>
</div>

And js file as:

app.controller('ctrl-1',function($scope){
    $scope.name = 'john';
});

app.controller('ctrl-2',function($scope){
   /*
    Here I want to change value of 'name' field which is in 'ctrl-1'
    */
});

How to achieve this in angular js?

Sangram Jagtap
  • 79
  • 1
  • 2
  • 7

1 Answers1

6

While it is possible to achieve this using controller inheritance or by other means, the best practice for this is to keep the value in a service/factory:

app.service('MyService', function() {

  this.name = 'John';

}

which you can then access by injecting the service into your controller(s)

app.controller('ctrl-1', function($scope, MyService) {

  $scope.name = MyService.name;

}

app.controller('ctrl-2', function($scope, MyService) {

  $scope.name = MyService.name;

}

EDIT: If you want to change the name in one of your controllers and have it reflect that change in the other controller it's best to use an object since you will be holding a reference to that object in your controllers.

app.service('MyService', function() {

  this.person = {};
  this.person.name = 'John';

}

app.controller('ctrl-1', function($scope, MyService) {

  $scope.person = MyService.person;


}

app.controller('ctrl-2', function($scope, MyService) {
  $scope.person = MyService.person;
  $scope.person.name = 'JFK';
  //MyService.person will now also be updated in 'ctrl-1'
}
Robin-Hoodie
  • 4,886
  • 4
  • 30
  • 63
  • If you want on a `link directive` change something base on the service variable, can you use `$watch` to watch that variable ? Can you watch a function that returns something and based on that trigger something ? – matiaslauriti Sep 23 '16 at 12:59
  • I want to change something like ctrl-1.$scope.name = 'abc' from ctrl-2 – Sangram Jagtap Sep 23 '16 at 13:00
  • 1
    @P0lT10n - Yes you can `$watch` a function and its return value is what is checked for changes. Do remember however that every time an Angular `digest` is run, that function is executed. So you don't want to add anything in there that will even cause a slight delay. – bPratik Sep 23 '16 at 13:19