【问题标题】:Angular js directive controller access scope property but returns undefinedAngular js指令控制器访问范围属性但返回未定义
【发布时间】:2016-02-23 10:14:42
【问题描述】:

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

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

指令:

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.k 时,我也得到未定义?!

【问题讨论】:

    标签: javascript angularjs angularjs-directive angular-controller


    【解决方案1】:

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

    您没有像选项那样为 filterType 设置默认值。

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

    【讨论】:

    • 忘记订单了!谢谢。我通过将属性传递给控制器​​来解决它。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多