如果JavaScript对象属性为空字符串

时间:2016-10-31 01:44:24

标签: javascript angularjs

我在Angular JS中创建一个表单,并希望禁用提交按钮(ng-disabled),直到与表单关联的模型全部填充,这意味着字符串不再为空,整数为no更长的零。

处理数字很容易,但其他不是价格的模型都存储在一个对象中,并且都是空字符串。我希望有一个简单的单行解决方案,我可以在ng-disabled中测试该对象是否不再包含任何属性的空字符串。

无论如何,这里有一些代码可以说清楚:

<div class="form-group">
    <label for="pickupDate" style="margin-top: 10px;">Pickup Date</label>
    <select name="pickupDate" ng-model="Oproperties.pickupDate">
        <option value="Tuesday">Tuesday - November 22nd</option>
        <option value="Wednesday">Wednesday - November 23rd</option>
        <option value="Thursday">Thursday - November 24th</option>
    </select>
</div>
<div class="form-group clear-fix">
    <div class="form-group" style="width:45%;float:left;">
        <label for="firstName">First Name</label>
        <input type="text" class="form-control" ng-model="Oproperties.firstName" placeholder="Jill">
    </div>
    <div class="form-group" style="width:45%;float:right;">
        <label for="lastName">Last Name</label>
        <input type="text" class="form-control" ng-model="Oproperties.lastName" placeholder="Smith">
    </div>
</div>
<div class="form-group">
    <label for="phone">Phone</label>
    <input type="text" class="form-control" ng-model="Oproperties.phone" placeholder="Phone Number">
</div>
<div class="form-group">
    <label for="email">Email</label>
    <input type="text" class="form-control" ng-model="Oproperties.email" placeholder="yourname@email.com">
</div>
<div class="form-group" ng-repeat="(key, value) in breads | groupBy: 'Type'">
    <label class="itemTitle">@{{key}}</label>
    <div ng-repeat="bread in value">
        <label for="@{{bread.Name}}">@{{bread.Name}}</label>
        <select name="@{{bread.Name}} quantity" ng-options="quantityOption as quantityOption.value for quantityOption in quantityOptions track by quantityOption.value" ng-model="bread.quantity" ng-change="calculate()"></select>
        </select>
        <p class="price">@{{bread.Price|currency}} @{{bread.details}}</p>
    </div>
</div>
<button ng-disabled="Oproperties.containsEmptyString()&&totalPrice===0" ng-click="submitOrder()" class="btn btn-default">Submit</button>

该对象如下:

 $scope.Oproperties=
    {
    pickupDate:"",
    firstName:"",
    lastName:"",
    phone:"",
    email:""
    }

所以基本上,我会做什么而不是目前只是概念性填充的Oproperties.containsEmptyString()

2 个答案:

答案 0 :(得分:2)

您可以将所有输入包含在名为form的{​​{1}}元素中,然后将myForm属性添加到输入中,然后设置

required

到你的提交按钮。

答案 1 :(得分:0)

您希望将元素包装在表单中并移动ng-click =&#34; submitOrder()&#34;在ng-submit =&#34; yourFormName。$ valid&amp;&amp; submitOrder()&#34;

这意味着只有在所有字段都经过正确验证后才会提交表单。