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?

3
  • are these siblings controllers ? Commented Sep 23, 2016 at 12:51
  • 1
    Possible duplicate of Share data between AngularJS controllers Commented Sep 23, 2016 at 12:52
  • @Andurit i want form to be accessible not variable values. And I'm new to angular Commented Sep 23, 2016 at 12:55

1 Answer 1

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'
}
Sign up to request clarification or add additional context in comments.

3 Comments

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 ?
I want to change something like ctrl-1.$scope.name = 'abc' from ctrl-2
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.