2014-11-06 126 views
0

我有自己的控制器(或鏈接功能)指令。模板內使用的指令。模板聲明如下:頁面控制器後執行的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 
     } 
    }; 

}]); 

回答

1

嗯,你在技術上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