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?
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'
}