NG模型在提交表格时未注册

ng-model not registering upon form submission

本文关键字:注册 表格 提交 模型 NG      更新时间:2023-09-26

我正在我的形式中玩ng-if。我希望用户能够选择一种颜色(通过ng-change触发功能),然后想要切换颜色,选择不同的颜色(触发不同的功能),并根据切换是否发生,从不同的结果下拉菜单中进行选择。

.HTML

<form name = "myForm" ng-submit = "submit()">
    <label> Select color </label>
    <select ng-model="myColor" ng-change = "setColorSelection()" class="form-control" 
        ng-options = "color as color for color in colors" required>
    </select>
    <br>
    <label> Switch colors? </label> <br>
    <label class="radio-inline">
        <input type="radio" ng-model="switchColors" value = "yes" >Yes</input>
    </label>
    <label class="radio-inline">
        <input type= "radio" ng-model = "switchColors" value = "no" >No</input>
    </label>
    <br>
    <div ng-show = "switchColors == 'yes'">
        <label> Which color will you switch to? </label>
        <select ng-model="myColorSwitched" ng-change = "setColorSelectionSwitched()" class="form-control" 
            ng-options = "color as color for color in colors">
        </select>
        <br>
    </div>

    <label> End result </label>
    <div ng-if = "switchColors == 'no'">
        <select ng-model="myEndResult" class="form-control"
            ng-options = "color as color for color in colorSelection" >
        </select>
    </div>
    <div ng-if = "switchColors == 'yes'">
        <select ng-model="myEndResult" class="form-control"
            ng-options = "color as color for color in colorSelectionSwitched">
        </select>
    </div>
    <br>
    <button type = "submit" class = "btn btn-default">Submit</button> 
</form> 
表单

字段按预期填充,但是,当我提交表单时,req.query.endResult 返回服务器未定义的,这意味着 ng-model = "myEndResult" 未提交。为什么会这样?

看起来

myEndResult永远不会设置为一个值,因此null .

假设您将"switchColors"启动为"否"或"是",以便实际上能够进入ng-if情况之一来设置"myEndResult",您应该检查myEndResult是否为null而不是空字符串。尝试在服务器上将其更改为以下内容:

if (myColor) req.myColor = myColor;
if (myEndResult) req.myEndResult = myEndResult;

如果 if 子句中只有对象,则检查对象的 0,null,未定义。

使用单选按钮使用$parent,如-

<label class="radio-inline">
        <input type="radio" ng-model="$parent.switchColors" value = "yes" >Yes</input>
    </label>
    <label class="radio-inline">
        <input type= "radio" ng-model = "$parent.switchColors" value= "no" >No</input>
    </label>