0

我已经构建了一个带有链接功能和控制器的简单指令。

我需要访问控制器范围内的属性集,但它一直说未定义。

指令:

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>'
    }
}]);

这是该指令的一个使用示例:

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

在控制器中,我有两个 console.log。

控制台日志一打印:

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

但随后控制台打印两个:

undefined

我需要访问指令控制器中的“filterType”,但是如何访问?

我可以看到范围内的所有内容都嵌套在一个叫做 k 的东西中,但是当我控制台日志 $scope.ki 也得到未定义?!

4

1 回答 1

0

您的控制器功能在您的链接功能之前执行。

filterType 没有选项的默认值。

在链接函数运行之前,未定义 fitlesType 值。为什么不在控制器函数中提供默认值?

于 2016-02-23T10:31:44.900 回答