函数始终返回undefined

时间:2015-11-20 13:24:02

标签: angularjs angularjs-directive

我遇到一个问题,getCurrentOption总是返回未定义的,我不能因为爱编码找出原因。因为我有两个功能相同的其他功能(coForms.toggleSelectcoForms.isSelectToggled),它们工作正常。

由于某种原因,select.currentOption中的coForms.selectOption设置正确,但是当我尝试在select.getCurrentOption中获取值时,它不再存在了......是丢失引用还是其他某处?我不太熟悉控制器作为语法,也没有把它连接到像这样的指令。

发生了什么事?

CoFormsCtrl

var coForms = this;

coForms.toggleSelect = function(select) {
    select.isToggled = !select.isToggled;
};

coForms.isSelectToggled = function(select) {
    return select.isToggled ? true : false;
};

coForms.selectOption = function(select, option) {
    select.currentOption = option;
};

/* This is always returning undefined atm, still search for the cause */
coForms.getCurrentOption = function(select) {
    return select.currentOption;
};

指令:

coForms.directive('coSelect', [function() {

    return {
        restrict: 'E',
        scope: {
            default: '=',
            list: '=',
            label: '@'
        },
        controller: 'CoFormsCtrl',
        controllerAs: 'co',
        templateUrl: 'app/views/components/co-forms/co-select.html',
        link: function(scope, element, attrs) {

        }
    };
}]);

指令模板:

<div class="co-select-form-control">
    <ul class="list-reset co-select">
        <li ng-click="co.toggleSelect(this)" class="co-select-option clickable">
            <span ng-bind="co.getCurrentOption(this) || default"></span>
            <ul ng-show="co.isSelectToggled(this)" class="list-reset bg-light co-select-dropdown">
                <li ng-repeat="option in list" ng-if="option !== co.getCurrentOption(this)" 
                        ng-click="co.selectOption(this, option)" ng-bind="option" class="co-select-option"></li>
            </ul>
        </li>
    </ul>
    <span class="co-select-icon">
        <i class="icon icon-keyboard-arrow-{{co.isSelectToggled(this) ? 'up' : 'down'}}"></i>
    </span>
</div>

然后我就这样使用它:

<co-select list="video.config.upload.status" default="video.config.upload.status[0]"></co-select>

1 个答案:

答案 0 :(得分:0)

改变这个:

/* This is always returning undefined atm, still search for the cause */
coForms.getCurrentOption = function(select) {
    return select.currentOption; 
};

对此:

coForms.getCurrentOption = function(select) {
    return select.currentOption || coForms.default;
};

在您的指令中,您已将指令HTML的default属性绑定到控制器范围的default属性。

coForms.directive('coSelect', [function() {

    return {
        restrict: 'E',
        scope: {
            default: '=',
            list: '=',
            label: '@'
        },
        controller: 'CoFormsCtrl',
        controllerAs: 'co',
        templateUrl: 'app/views/components/co-forms/co-select.html',
        link: function(scope, element, attrs) {

        }
    };
}]);