22

我有以下多选框:

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

在我的控制器中,我在初始化时执行此操作:

$scope.form.Slides = [];

如果 Slide 数组中有幻灯片,我希望表单的这个元素有效。这些是动态添加的——它是一种用户可以添加幻灯片的幻灯片桶。

但是我不明白 ngRequired 的工作原理……如果我将其更改为,data-ng-required="true"那么我的表单看起来还不错,但当然它并没有达到我想要的效果。如果我使用form.Slides.length > 0which 来检查我真正想要的东西,这不仅不起作用,而且会扰乱我的表单结构,我的一个元素似乎会随机消失。

使用它的正确方法是什么?文档在这方面非常稀少。

4

1 回答 1

25

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.

于 2013-10-09T19:29:11.327 回答