gespinha
gespinha

Reputation: 8497

Access $rootScope through controller not working

I have the following code, which is trying to add a variable to the $rootScope through a directive and trying to get that value and show it inside a controller element.

But when I click the links inside the directive, it doesn't display the new $rootScope variable.

https://plnkr.co/edit/P7Lq7h13RmXryFC0uBMi?p=info

var mod = angular.module('myApp', []);

mod.directive('mainMenu', menuDirec);

function menuDirec($rootScope){
  return {
    templateUrl: 'menu.html',
    restrict: 'A',
    controller: menuControl,
    controllerAs: 'vm'
  };

  function menuControl(){
    var vm = this;

    vm.menu = {
      'one': 'Link 1',
      'two': 'Link 2',
      'three': 'Link 3',
      'four': 'Link 4'
    };
    vm.clickMenu = function(slug){
      $rootScope.active = slug;

      console.log($rootScope);
      console.log(slug);
    }
  }
}

mod.controller('content', contentControl);

function contentControl($scope, $rootScope){
  $scope.title = $rootScope.active;
}

Upvotes: 0

Views: 224

Answers (1)

georgeawg
georgeawg

Reputation: 48968

Change the HTML to access the title as a function

  <div ng-controller="content">
    <h1>{{ title() }}</h1>
  </div>

In your JS make it a function

mod.controller('content', contentControl);

function contentControl($scope, $rootScope){
  $scope.title = function () {
    return $scope.active;
  };
}

Then on each digest cycle, the $watch attached to the {{title()}} will execute the function and update the DOM as the value of $scope.active changes.

The UPDATE on PLNKR.


Best practice

Avoid cluttering $rootScope with variables. Instead use isolate scope and two-way binding. For more information, see AngularJS Comprehensive Directive API - scope.

As example

mod.directive('mainMenu', menuDirec);

function menuDirec(){
  return {
    templateUrl: 'menu.html',
    restrict: 'A',
    controller: menuControl,
    controllerAs: 'vm',
    scope: { active: '=' },
    bindToController: true
  };

  function menuControl(){
    var vm = this;

    vm.menu = {
      'one': 'Link 1',
      'two': 'Link 2',
      'three': 'Link 3',
      'four': 'Link 4'
    };
    vm.clickMenu = function(slug){
      vm.active = slug;
      console.log(slug);
    }
  }
}

HTML

<body ng-app="myApp">

  <nav main-menu active="title"></nav>

  <div ng-controller="content">
    <h1>{{ title }}</h1>
  </div>

</body>

The DEMO on PLNKR

Upvotes: 2

Related Questions