Angularjs: directive loading order

I have two directives on one page, but on another element. Something like that:

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

In directiveOne, I create some variable (say, $scope.pageConfig.variable). I want DirectiveTwo to use this variable.

Problem - directiveOne does not always load before the directive.

The question is, is there a way to make sure directiveOne is loaded before the Two directive so that the variable is accessible to the Two directive?

Thank:)

UPDATE: I found that the answer should be to use the controller in directiveOne as follows:

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

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

+4
4

. . , , ( DOM) -

DOM, DOM

, , . . , , , " ".

, $scope ( : ($ scope), : function (scope)), . , :)

+3

A B:

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);
      }
    }
  });

Plunk ,

+6

, preLink. preLink :

return {
  link: {
    pre: function preLink(scope, element, attrs) {
      // put your code here
      // code in here of parent will be executed before child (top down).
    },
    post: function postLink(scope, element, attrs) {
      // code in here of parent will be executed after child (bottom up).
    }
  }
};
+4

, , .

,

App.directive('myDirective', function() {
  return {
      restrict: 'AE',
      replace: 'true',
      link: function ($scope, element, attrs) 
      {
          $scope.test = "testme"
      } 
  };
});


App.directive('mySecondDirective', function() {
  return {
      restrict: 'AE',
      replace: 'true',
      link: function ($scope, element, attrs) 
      {
          $scope.$watch('test', function() {
                       alert('hey, myVar has changed!');
       });
      } 
  };
});

- ,

$scope.test = "Waiting to update";


setTimeout(function () {
    $scope.$apply(function () {
          console.log($scope.test);
    });
}, 2000);

Hope this helps you!

-2
source

All Articles