Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: Directives load order

I have two directives on the same page, but on a different element. Something like that:

<div directive-one>
    <div directive-two></div>
</div>

In directiveOne, I create some variable (let's say, $scope.pageConfig.variable). I want directiveTwo to use this variable.

The problem - directiveOne not always loads before directiveTwo.

The question is - is there a way to make sure directiveOne loads before directiveTwo, so that the variable would be available for directiveTwo?

Thanks :)

UPDATE: I've found the answer is supposed to be to use a controller in directiveOne like this:

return {
controller: function($scope){ $scope.variable = variable; },
link : ...
}

The problem is that I get an error [$injector: unpr] when using it this way. Should this solve my issue? Any idea why this creates an error for me?

like image 867
yccteam Avatar asked Dec 20 '22 13:12

yccteam


1 Answers

How about requiring directiveA in directiveB:

var myApp = angular.module('myapp', [])
.run(function(){

});

myApp.directive('fooDirective', function() {
    return {
      restrict: 'A',
      controller: function(){
        this.pageConfig = {
          someVaraible: 'value from foo'
        };
      }
    }
  });

  myApp.directive('barDirective', function() {
    return {
      restrict: 'A',
      require: '^fooDirective',
      link: function(scope, element, attr, fooDirectiveController){
        console.log(fooDirectiveController.pageConfig);
      }
    }
  });

Here's a Plunk and more information on extending directives, and here some more info

like image 141
miron Avatar answered Dec 30 '22 08:12

miron