2016-04-25 41 views
0

我正在玩ng-if在我的表單中。我希望用戶能夠選擇一種顏色(它通過ng-change觸發一個函數),然後想要切換顏色,選擇不同的顏色(觸發不同的功能),並根據切換是否發生,選擇不同的結果下拉菜單。ng-model不在表單提交時註冊

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-模型=「myEndResult」不提交未定義。這是爲什麼發生?

+0

你的「submit()」函數是怎麼樣的? 你最初初始化JavaScript中的「myEndResult」? – nicost

+0

@nicost我已經添加了我的提交功能到 –

+0

這個問題,因爲它似乎「myEndResult」永遠不會被設置爲一個值,因此'null'。 所以(假設你啓動「switchColors」爲「no」或「yes」以便能夠進入ng-if情況之一來設置'myEndResult'),你應該檢查myEndResult爲null而不是emptystring。 嘗試在服務器上將其更改爲以下內容: if(myColor')req.myColor = myColor; if(myEndResult)req.myEndResult = myEndResult; (如果你只是在if子句中的對象,你檢查0,null,undefined的對象) – nicost

回答

0

隨着單選按鈕使用$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> 
+0

我只是能夠解決這個問題,實際上,我的提交功能有一個錯字。它使用值而不是ng值。我很好奇爲什麼每個人都說ng-value更好,因爲在這裏的官方文檔:https://docs.angularjs.org/api/ng/input/input%5Bradio%5D他們使用的值而不是ng值 –

+0

ng-value將其綁定到$ scope-variable。假設你有ng-value =「yes」,它會查找一個名爲'$ scope.yes'的變量並取其值。如果沒有定義,它顯然是空的。價值取而代之的是價值「是」。 – nicost

0

,因爲它似乎,myEndResult永遠得不到的設定值,因此是null

假設你開始「switchColors」要麼「沒有」或「是」,居然能進入NG-IF的情況下設置「myEndResult」,你應該爲空檢查myEndResult而不是emptystring之一。 嘗試將其更改爲在服務器上執行以下操作:

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

如果您在如果子句中有剛的對象,你檢查0,null,未定義的對象。