javascriptangularjsangularjs-directiveangular-local-storage

AngularJS : Best way to use directive


Explanation:

I created a header directive for my angular application. By using this directive we are loading template by using templateUrl property of attribute based on some conditions.

HTML:

<div header></div>

directive:

app.directive('header', ['LS', function(LS) {
'use strict';

var user = LS.getData() === 'true' ? true : false;
return {
    restrict: 'A',
    replace: true,
    templateUrl: user ? 'withlogin-header.html' : 'withoutlogin-header.html',
    controller: ['$scope', 'LS', function ($scope,LS) {
      $scope.login = function() {  
      return LS.setData(true);
      }
      $scope.logout = function() {
      return LS.setData(false);
      }
    }]
  }
}]);

withlogin-header.html:

<div>
    User  is logged in !!!
    <input type="button" ng-click="logout()" value="Logout"/>
</div>

withoutlogin-header.html:

<div>
    Hey buddy, log in !!!
    <input type="button" ng-click="login()" value="Login"/>
  </div>

Requirement :

We have to display different headers based on the user roles.i.e if user was not login then we have to display normal header with login button and if user already login then we have to display different header with logout button.

Challenge we are facing :

header directive is not working properly. when we click on the login button from withoutlogin-header.html it not loading another template withlogin-header.html based on the defined condition in the templateUrl property of the directive.

I tried so far:

Plnkr : http://plnkr.co/edit/w7AyUjSNA1o5NJp6tD1p?p=preview


Solution

  • Checkout this plunker i have created an amazing directive for fetching dynamic header template from server.

    I have made some little changes to your code as well. Hope it will help you surely...

    http://plnkr.co/edit/GWIozm?p=preview