2014-07-22 84 views
4

我在同一页面上有两个指令,但在另一个元素上。 类似的东西:Angularjs:指令加载顺序

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

在directiveOne,我创建一些变量(比方说,$scope.pageConfig.variable)。 我想指令两个使用这个变量。

问题 - directiveOne不总是在directiveTwo之前加载。

问题是 - 有没有办法确保directiveOne在directiveTwo之前加载,以便该变量可用于directiveTwo?

谢谢:)

更新: 我已经找到了答案应该是在directiveOne使用控制器这样的:

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

的问题是,我得到一个错误[$注入器:unpr]以这种方式使用时。这应该解决我的问题吗?任何想法为什么这会给我造成一个错误?

+2

您可以给予指令1更高的优先级。请参阅https://docs.angularjs.org/api/ng/service/$compile - 优先 – hutingung

+0

请显示您的指令代码。你在哪里把你的逻辑放在两个指令中,postLink? – runTarm

+0

我把逻辑放在链接函数中。我试图使用控制器,这应该工作,但我得到一个错误。现在我看到每次将控制器放入我的任何指令时都会出现错误。不管控制器中有什么。奇怪... – yccteam

回答

3

我已经找到了答案。 一个解决方案可以是miron的解决方案。问题是,它为正在等待孩子的指令(在问候DOM树)母公司指令 -

你可以要求它父DOM元素上,或同一DOM元素

对我而言,另一种解决方案是使用指令的控制器。 This blog post解释得非常好。简而言之,控制器是按照dom树的读取顺序激活的,而链接正在被读取。

我的问题是,您必须接受控制器实际接受范围的$ scope(如controller:function($ scope)而不是controller:function(scope))。不直观,但这就是它的原理:)

-2

如果变量会更新,您可以随时在变量上设置一个监视。

这里有一个简单的例子,

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

希望这将帮助你!

+4

这不太好。 考虑dom元素与指令一起创建的情况(如kendoui小部件),并且此指令负责创建选项... – yccteam

+0

在最初的问题中没有说明该情况 – Adam

6

如何要求directiveA在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); 
     } 
    } 
    }); 

这里有一个关于延伸指令一个Plunkinformation,这里some more info

4

如果你想在孩子之前在父指令中运行一些代码,你可以把你的代码放在preLink函数中。preLink功能可以像这样指定:

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