1

When I click a button in myCtrl controller. The ng-model of myCtrl2 should also be changed with ng-model of current controller:

<div ng-app="myApp" >
<div  ng-controller="myCtrl">
     <input type="text" ng-model="name">
     <button ng-click="just()">submit</button>
</div>
<div  ng-controller="myCtrl2">
    <input type="text" ng-model="name2">
</div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name="before";
    $scope.just = function()
    {
       $scope.name="after";

       $scope.name2="after";   /////  this is not working


    }
});
</script>
1
  • Add watch to listen changes or broadcast from rootscope. Commented Jan 25, 2016 at 5:44

3 Answers 3

3

There are several way to solve this. One of them is using $emit event. You can dig about it deeper here.

But for quick reference, I provide you a Plunkr here. Please check it out.

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

app.controller('myCtrl', function($rootScope, $scope) {
   $scope.name="before";
   $scope.just = function(){
      $scope.name="after";
      $rootScope.$emit('update');
   }
   }).controller('myCtrl2', function($rootScope, $scope){
      $rootScope.$on('update', function(){
      $scope.name2 = "after";
   })
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yes you're welcome. So please mark this as the accepted answer to help people who face the same situation as you had, in the future. Thans.. :)
HOW TO ACCEPT THIS ANSWER
There should be a check icon in the left side of the answer.
0

You would need to make a service which you would then inject into your controllers.

https://docs.angularjs.org/guide/services

Comments

0

you can use $rootScope for this:

var app = angular.module('plunker', []);
app.controller('myCtrl', function($rootScope, $scope) {
   $scope.name="before";
   $scope.just = function(){
      $scope.name="after";
      $rootScope.nameInRootScope=$scope.name;
   }
   }).controller('myCtrl2', function($rootScope, $scope){
      $scope.name2 = $rootScope.nameInRootScope;
   })
});

Comments

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.