Angular js directive controller access scope property but returns undefined

1k Views Asked by At

I have built a simple directive with a link function and a controller.

I need to access a property set in the scope in the controller but it keeps saying undefined.

The directive:

app.directive('calendarSelectFilter', ['$log', 'eventService', function( $log, eventService ) {
    return {
        restrict: 'E',
        scope: {
            startingValue: '=',
            selected: "=value",
            filterType: '='
        },
        controller: function( $scope ){

            var options =[];
            console.log($scope); //LOG ONE
            console.log($scope.filterType);  //LOG TWO
            switch( $scope.filterType ){
                case 'environment':{
                    console.log( 'fetching envOptions' );
                    options = eventService.getSchemaLabelsAsArray('envOptions');
                } break;
                case 'event-type':{
                    options = eventService.getSchemaLabelsAsArray('eventNames');
                } break;
            }

            $scope.options = options;
        },
        link: function( scope, element, attrs ){
            if( !attrs.filterType ){
                $log.error( 'No filterType passed to the calendarSelectFilter directive' );
            }
            scope.filterType = attrs.filterType;
            scope.selected = scope.startingValue;
        },
        template: '<select ng-model="selected" ng-options="option for option in options">{{option}}</select>'
    }
}]);

This is a use example of the directive:

<calendar-select-filter value="filter_options.environment" filter-type="environment"></calendar-select-filter>

In the controller i have two console.log.

Console log one prints:

k {$id: "007", $$childTail: null, $$childHead: null, $$prevSibling: null, $$nextSibling: null…}
$$asyncQueue: Array[0]
$$childHead: null
$$childTail: null
$$destroyed: false
$$isolateBindings: Object
$$listenerCount: Object
$$listeners: Object
$$nextSibling: a.$$childScopeClass.$$childScopeClass
$$phase: null
$$postDigestQueue: Array[0]
$$prevSibling: null
$$watchers: Array[6]
$id: "007"
$parent: a.$$childScopeClass.$$childScopeClass
$root: k
filterType: "environment"
options: Array[0]
selected: undefined
startingValue: undefined
this: k
__proto__: k

But then console two prints:

undefined

I need to access the "filterType" in the directives controller, but how?

I can see that the scope has everything nested inside something called k, but when i console log $scope.k i also get undefined ?!

1

There are 1 best solutions below

1
On BEST ANSWER

Your controller function executes before your link function.

You don't have a default value for filterType like you do for options.

The fitlesType value isn't defined until the link function runs. Why not provide a default value in your controller function?