cyber_ua cyber_ua - 1 month ago 12x
Javascript Question

How do i can run directive function before controller?

I need call directive function ( i need scope ) before controller.

var app = angular.module('docsRestrictDirective', []);

app.controller('Controller', ['$scope', function($scope ) {

app.directive('ngMyDer', function() {
return {
restrict: 'A',
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
scope.changeDerictive = function() {



as requested this is the example with ui-router. first we will define a controller for the base of the app.

<body ng-app="myApp" ng-controller="AppBaseCtrl">
    <main role="main">
        <div ui-view></div>

now in the ui router we will define our base route:

.config(function ($stateProvider, $urlRouterProvider) {
            .state('desiredRoute', {
                url: '/desiredRoute',
                templateUrl: 'views/pathToTemplate.html',
                controller: 'MyViewCtrl'

so what will happen? the base controller runs, we can initialize desired scope variables, then we run the directives and then we run our required controller.

so you have the directive which runs before the needed controller.

if we want this to be cleaner with ui-router we can define the routes like this:

in the routes config:

  .state('dashboard', {
        url: '/dashboard',
        templateUrl: 'views/templates/dashboard/dashboard-base.html',
        controller: 'DashboardBaseCtrl',
        abstract: true
    .state('dashboard.main', {
        url: '/main',
        templateUrl: 'views/templates/dashboard/dashboard-main.html',
        controller: 'DashboardMainCtrl'

then in the view for the dashboard-base:

<div myDirective></div>
<div ui-view></div>

and of course define in the base controller what ever you want and as you can see... base controller runs then directive then our desired controller so directive runs before the controller...


I have created a small plunker like you asked... you will see here that with no timeout the directive is called before our main controller does using a base controller my example is the first example in the answer

plunker with answer