angularjsvalidationangularjs-ui-utils

How can I validate an ng-repeated dropdown category selector?


I created a nested category model. In order to select a category for a product, you see a dropdown with the main categories. When you select one, a new dropdown is added to the right with the child categories to the one you selected. This repeats until you reach the last level. When this happens $scope.product.category_id is set. I want to invalidate the whole set of fields when $scope.product.category_id is null.

I've been using angular-bootstrap-show-errors for validation and I tried to mix it with ui-utils to achieve this one, using a custom function: validate_category().

Here's the HTML I used:

<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>

And this is my simple validation function:

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

But this is not working. Ideas?

EDIT: I just realized, that the problem with this is that the validation function on ui-validate is executed after the ng-change function, so it's never able to check the $scope.product.category_id update.


Solution

  • This is not the ideal answer but it's the best I could get. Shame on me, this was too simple:

    <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> 
    

    That's it, just added the required attribute. The problem with this is that since the I'm not validating product.category_id but just validating all the dropdowns to be not empty. I guess I 'll have to rely on the code on select_category().