5

我创建了一个嵌套类别模型。为了选择产品的类别,您会看到一个包含主要类别的下拉菜单。当您选择一个时,将在右侧添加一个新的下拉列表,其中包含您选择的子类别的子类别。重复此过程,直到您到达最后一个级别。发生这种情况时$scope.product.category_id设置。我想在$scope.product.category_idis时使整个字段集无效null

我一直在使用angular-bootstrap-show-errors进行验证,我尝试将它与ui-utils混合使用自定义函数来实现这一点:validate_category().

这是我使用的 HTML:

<span ng-repeat="parent_id in category_dropdown_parents" show-errors="{ skipFormGroupCheck: true }">
    <select class="form-control" name="category_id"
        ng-init="selected_category[$index] = init_select($index);"
        ng-model="selected_category[$index]"
        ng-options="category.name for category in (categories | filter : { parent_id: parent_id } : true ) track by category.id "
        ng-change="select_category(selected_category[$index], $index)"

        ui-validate="'validate_category()'" // added this to work with ui-utils

        >
    </select> 
    <span ng-if="$index+1 != category_dropdown_parents.length">/</span>
</span>

这是我的简单验证功能:

$scope.validate_category = function() {
    return  (   $scope.product.category_id !== null 
            &&  $scope.product.category_id !== undefined);
}

但这不起作用。想法?

编辑:我刚刚意识到,这个问题是验证函数在函数ui-validate之后执行ng-change,所以它永远无法检查$scope.product.category_id更新。

4

2 回答 2

4

您的选择正在使用

ng-model="selected_category[$index]"

但验证功能正在使用

$scope.product.category_id

它不应该使用

ui-validate="'validate_category($index)'"

$scope.validate_category = function($index) {
    return($scope.selected_category[$index] !== null 
    && $scope.selected_category[$index] !== undefined);
}
于 2015-06-24T20:46:09.840 回答
4

这不是理想的答案,但这是我能得到的最好的答案。真可惜,这太简单了:

<select class="form-control" name="category_id"
    ng-init="selected_category[$index] = init_select($index);"
    ng-model="selected_category[$index]"
    ng-options="category.name for category in (categories | filter : { parent_id: parent_id } : true ) track by category.id "
    ng-change="select_category(selected_category[$index], $index)"

    required // !!!

    >
</select> 

就是这样,只是添加了required属性。这样做的问题是,因为我没有验证product.category_id,而只是验证所有下拉列表不为空。我想我将不得不依赖于代码select_category()

于 2015-06-26T17:15:24.163 回答