Angular js 指令控制器访问范围属性,但返回未定义

Angular js directive controller access scope property but returns undefined

本文关键字:返回 未定义 属性 范围 js 指令控制器 访问 Angular      更新时间:2023-09-26

我构建了一个简单的指令,其中包含链接函数和控制器。

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

该指令:

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>

在控制器中,我有两个控制台.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.k 时,我也未定义?!

控制器函数在链接函数之前执行。

您没有像选项那样具有 filterType 的默认值。

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