页面控制器后执行的AngularJS指令的控制器

页面控制器后执行的AngularJS指令的控制器

问题描述:

我有自己的控制器(或链接功能)指令。模板内使用的指令。模板声明如下:页面控制器后执行的AngularJS指令的控制器

when('/dashboard', { 
     templateUrl: 'views/dashboard/dashboard.html', 
     controller: 'DashboardCtrl',    
}). 

的问题是指令的控制器之后DashboardCtrl执行,因为我要使用通过指令设置的值。我如何才能使指令的控制器先执行(在DashboardCtrl之前)?

angular.module('directives') 
    .directive('timeRangePicker', ['timeService', function (timeService) { 
    return { 
     restrict: 'E', 
     scope: { 
      ngModel: '=' 
     }, 
     templateUrl: 'views/time-range-picker.html', 

     link: function ($scope, elem, 

      $scope.ngModel = {}; 

      $scope.ngModel.dateFrom = today(); // initial value 
      $scope.ngModel.dateTo = tomorrow(); // initial value 
     } 
    }; 

}]); 

嗯,你在技术上CANT

(页面控制器将模板evalutation之前执行)和我不会骗你,你正在尝试做的,似乎是非常不好的原因,但无论如何,在这里我将如何做到这一点:

我会让我的DashboardController等待(注意)由该指令控制器初始化范围内的属性。所以这样,我会在执行指令控制器后从页面控制器执行函数。

但又一次:你为什么要这么做?页面根控制器的行为不应该依赖于它的内容。

父控制器上:

$scope.state = { directiveInit : false }; // dont use direct primitive else the child directive wont update it on the parent scope 
$scope.$watch("state.directiveInit", function(init) { if(init==true) { /* do the stuff*/}}); 

在向链路FN或控制器:

$scope.state.directiveInit = true; 
+0

感谢答案。其实我有选择时间范围的指令。即它显示2个日历字段。指令具有自定义'ngModel'属性,我的'DashboardCtrl'想要读取指令的'ngModel'属性的初始值,但是它在'DashboardCtrl'执行后设置。我编辑了问题(添加了我的指令代码)。你能给我一些想法如何做得更好吗?再次感谢您的回答 – MyTitle 2014-11-06 18:49:32