0

I'm new to Angular, and I struggle with validating a multi select input with ngOptions attribute. I want the field to be required, so the user must chose at least one option. However the validation methods Angular have simply doesn't work in my case, Here's what I've tried:

<form name="products" novalidate>
    <div class="form-group">
        <label for="select-product">Chose product/s</label>
        <select id="select-product" name="selectedProduct" class="form-control"
                required
                multiple
                ng-model="selectedProduct"
                ng-options="product.name for product in products">
        </select>
    </div>
    <button class="btn btn-primary pull-left" ng-click="products.selectedProduct.$valid && goToChildrenId()">Next</button>
</form>

Even if I chose a product and I can see that the form class switch from .ng-invalid to .ng-valid, the function goToChildrenId() doesn't run.

Also, if I add {{products.selectedProduct.$valid}} at the bottom, when I refresh the page I can see "false" for a second but it disappear, why?

If it's relevent, this is the controller:

adminCheckout.controller('productsCtrl', function($scope, $http, wpMiniapps, $location, $rootScope){
    $scope.products = [];
    var url = wpMiniapps.routeUrl("getProducts");
    $http.post(url, {}).then(function(res){
        $scope.products = res.data.data;
    }, function(err){
        console.log(err);
    });

    $scope.$watch('selectedProduct', function (newVal) {
        $rootScope.globalData.products = newVal;
    });

    $scope.goToChildrenId = function(){
        $location.path('/select-children');
    };
});

I searched the web but nothing seems to work in my case.

I will really appreciate any help.

1 Answer 1

1

You have a variable name collision which is causing the problem: the form is named products and this ends up as a $scope variable. But it collides with $scope.products = [] from the controller. Simply renaming the form to, e.g., productsForm solves the problem:

<form name="productsForm" novalidate>
    ...
    <button class="btn btn-primary pull-left" ng-click="productsForm.selectedProduct.$valid && goToChildrenId()">Next</button>
</form>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.