Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ng-required vs required

Tags:

I have the following multi select box:

<select      multiple="multiple"      data-ng-model="rightSelected"      data-ng-options="slide as slide.SlideBarcode for slide in form.Slides"      data-ng-required="form.Slides.length > 0"  /> 

In my controller I do this at initialization:

$scope.form.Slides = []; 

I want this element of the form to be valid if there are slides in the Slide array. These are added dynamically- it's kind of a slide bucket users can add slides to.

But I'm not getting how the ngRequired stuff works... if I change it to data-ng-required="true" then my form looks okay, but of course it doesn't do what I want. If I use the form.Slides.length > 0 which is checking for what I really want, not only does this not work, but it messes with my form structure, one of my elements vanishes seemingly at random.

What is the proper way to use this? The docs are pretty sparse on this one.

like image 638
Nicros Avatar asked Oct 07 '13 17:10

Nicros


People also ask

How to use ng required?

Definition and UsageThe ng-required directive sets the required attribute of a form field (input or textarea). The form field will be required if the expression inside the ng-required attribute returns true. The ng-required directive is necessary to be able to shift the value between true and false .

What is Ng form in AngularJS?

The ng-form Directive in AngularJS is used to create a nested form i.e. one form inside the other form. It specifies an inherit control from the HTML form. It creates a control group inside a form directive which can be used to determine the validity of a sub-group of controls.


1 Answers

Check out this post:

What is the difference between required and ng-required?

From what I think you're trying to do, I think you're using the ng-required attribute wrong. The ng-required attribute is for when you want to conditionally require an input or not. I'm guessing in your case you always want that input to be required.

As per your comments, if you don't want to manage to any functions, I would put all of these in one function

$scope.isFormValid= function(){     if (form.Slides.length > 0 && myForm.$valid)         return true; } 

and then

ng-disabled="isFormValid()" 

This may not be the most elegant solution but it works. Let me know if that's not what you wanted.

like image 162
NicolasMoise Avatar answered Sep 18 '22 18:09

NicolasMoise