0

I'm having a bit of trouble understanding scopes and the relation between scopes in a directive and scope in a controller..

I have a directive displaying a navbar like this, in the navbar I want to display a name, that i stored using localStorage

(function (module) {

    var navbar = function () {

        return {
            restrict: "AE",
            controller: function ($scope, localStorage) {
                $scope.name = localStorage.get("name");
            }, 
            templateUrl: "/app/NSviewer/templates/nav.html"
        };

    };

    module.directive("navbar", navbar);

}(angular.module("anbud")));

Now when this page is loaded for the first time the localStorage haven't set the name value. So the navbar gets name = null. Then the controller does:

localStorage.add("name", name);

and the name is set, if I refresh the page the navbar is loaded again, this time the name is stored in localstorage and it is displayed correctly.

So I want to do something like $scope.name = 'John Smith' in the controller and then have my directive / navbar update.

ganjan
  • 7,356
  • 24
  • 82
  • 133

1 Answers1

2

Storing a value to be shared between a controller and a directive in local storage is overkill. Typically you do the following:

(function() {
  'use strict';

  angular
    .module('app')
    .directive('dashboard', dashboard);

  function dashboard() {

    var directive = {
      restrict: 'E',
      controller: 'DashboardController',
      controllerAs: 'vm',
      bindToController: {
         msg: '@'
      },
      scope: {},
      templateUrl: '/templates/dashboard/dashboard.html'
    };

    return directive;
  }

  angular
    .module('app')
    .controller('DashboardController', DashboardController);

  DashboardController.$inject = [];

  function DashboardController(){
    var vm = this;
    vm.msg = 'Hello World'      
  }
})();

Some things to note:

  • The bindToController can accept an object. This is something that could only accept a boolean pre angular 1.4. Now it can act just like the scope property and attach stuff to be used by your controller to pass data.
  • The use of @ means that it's a 1 way data bound string. = sets up a two-way bound relationship and there's also the & property. See this post for an overview of what they all mean
  • Another difference between what I'm doing is that I'm using var vm = this as opposed to injecting $scope This is quite a popular approach nowadays and means you don't get riddled with scope soup. But you can think of it as a way to do the same thing essentially (that is binding stuff but it cannot listen for events so please remember that)

Good luck

Community
  • 1
  • 1
Katana24
  • 8,706
  • 19
  • 76
  • 118