WelcomeTo
WelcomeTo

Reputation: 20571

AngularJS directive's controller executed after page controller

I have directive with its own controller (or link function). Directive used inside template. Template declared like this:

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

The problem is that Directive's controller executed after DashboardCtrl, because I want to use values which are set by directive. How I can cause directive's controller to be executed first (before 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
        }
    };

}]);

Upvotes: 0

Views: 91

Answers (1)

Pierre Gayvallet
Pierre Gayvallet

Reputation: 2953

Well, you technically CANT ( page controller will be executed before template evalutation )

And I wont lie to you, what you are trying to do seems to be for very bad reasons, but anyway, here how I would do it :

I would make my DashboardController wait (watch for) a property in the scope to be initialized by the directive controller. So this way, i would execute the function from the page controller after the executing of the directive controller.

But once again : why are you trying to do this ? A page root controller behaviour should not depends on it's content.

on parent controller :

$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*/}});

on the directive link fn or controller :

$scope.state.directiveInit = true;

Upvotes: 1

Related Questions