0

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;
}
1
  • Don't you need to add $rootScope to menuControl function? Commented Feb 11, 2016 at 17:02

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.