0

I have a service that will auth my user and get a token. I'm consuming it on the mainController which is appended to the body (index.html)

That should be the frist thing to do in my app.

In my index.html are 2 directives (which are consuming a service that needs that token)

<body ng-controller="mainController">
<div class="row" ng-if="token">
   <div directive1></div>
 </div>
 <div class="row" ng-if="token">
    <div directive2></div>   
  </div>
</body>

It throws an error because the token is not yet defined when the directives are used.

 angular.module('app').directive('directive1', function () {
  return {
  templateUrl: directive1.html,     
  controller: function (thingsService) {
        //
   }
 }
});

I've got a solution based on ng-if == token on html directive call (index.html)

This does the job, but I'm not really satisfied. Is there a better solution? I've seen a solution of watches already.

noneJavaScript
  • 835
  • 3
  • 21
  • 41

1 Answers1

0

The following solution is not better than the ng-if, but maybe cleaner. The idea is to pass the token to the directive as a parameter (instead of the service). The directive watches for changes on the token and react accordingly.

Here is a jsfiddle demonstrating how to implement such service:

.directive('aDirective',
    function() {
      return {
        restrict: 'EAC',
        scope: {
                token: '=', // <= declare a token parameter
            },
        link: function($scope, element, attrs, controller) {
          var controllerOptions, options;
          $scope.$watch('token', function(value){
            // do stuff here
          });        
        }
      };
    }
  )

I also suggest you to have a look at this answer, which demonstrate how to wait for a condition/initialisation before loading an angular module. You could then first initialise your token, then load your module.

Community
  • 1
  • 1
Derlin
  • 9,572
  • 2
  • 32
  • 53