Robert van der Spek Robert van der Spek - 4 months ago 6
AngularJS Question

Variable not updated after change in different controller

I have the following code:

<!DOCTYPE html>
<html ng-app="App">

<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>

<body>
<div>

<div ng-controller="Ctrl1">Ctrl1.option = {{option}}</div>

<div ng-controller="Ctrl2">Crtl2.thisOtpion = {{thisOption}}</div>

</div>

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js" ng:autobind></script>
<script>
angular.module("App", []).controller("Ctrl1", function($scope) {
$scope.option = 1;
});

angular.module("App").controller("Ctrl2", ["$scope", "$controller",
function($scope, $controller) {

$scope.thisOption;

var Ctrl1Proxy = $scope.$new();
$controller("Ctrl1", {$scope : Ctrl1Proxy});
Ctrl1Proxy.option = 0;
$scope.thisOption = Ctrl1Proxy.option;



}
]);

</script>
</body>

</html>


The result is: 1

Why isn't the variable option updated to 0? And what should I do to obtain this result? I already tried using $apply also in combination with $timeout. But without any success.

Thanks!

Answer

In this case you should use $rootScope

html

 <div ng-controller="Ctrl1">

      <div ng-controller="Ctrl2">{{option}}</div>

    </div>

JavaScript

angular.module("App", []).controller("Ctrl1", function($rootScope) {
        $rootScope.option = 1;
      });

      angular.module("App").controller("Ctrl2",  ["$scope", "$location", "$controller", "$timeout","$rootScope",
        function($scope, $location, $controller, $timeout,$rootScope) {
            // Forward if user is not a manager



                   $rootScope.option = 0;



        }
      ]);

reference