Angularjs rootscope not geting updated

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    </head>
    <body ng-app="myApp" >
        <div ng-controller="myCtrl1">
            <input type="text" ng-model="name"/>
            <button ng-click="getName()">Submit</button>
        </div>
        <div ng-controller="myCtrl2">
            **_{{user}}_**
        </div>
        <script>
            var app = angular.module('myApp',[]);

            app.controller('myCtrl1', function($scope, $rootScope){
                $scope.getName = function(){
                    debugger;
                    _**$rootScope.userName = $scope.name;**_
                }
            });

            app.controller('myCtrl2', function($scope, $rootScope){
                **_$scope.user = $rootScope.userName;_**
                console.log($scope.user);
            });
        </script>
    </body>
</html>

This is my code onclick of the button i have to update that in another controller but it is not happening.
Why two way binding is not working?

When Angular initializes both controllers, the property $rootScope.userName is undefined, and this is the value that will be assigned to $scope.user. Once you fill in the input and click submit, the property will be created, but controller myCtrl2 has already done the assignment and has no way of knowing that the value has changed.

One way to get this working is to create an object on $rootScope and assign that to $scope.user - that way when a property is changed on the object, that change will be reflected in the template for myCtrl2.

Other ways to do it include setting up a watcher, to observe when a property on $rootScope changes and update the local $scope property accordingly, or use a service that is shared between the two controllers.

Thanks for the help.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.