Robert van der Spek Robert van der Spek - 4 years ago 83
AngularJS Question

Variable not updated after change in different controller

I have the following code:

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

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


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

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


<script src = "" ng:autobind></script>
angular.module("App", []).controller("Ctrl1", function($scope) {
$scope.option = 1;

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


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




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.


Answer Source

In this case you should use $rootScope


 <div ng-controller="Ctrl1">

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



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;



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download