2016-11-29 93 views
0

我有一個下拉列表,當用戶從下拉列表中選擇任何選項時,每個選擇都會出現一個文本框。 HTML的將動態文本框中的數據發送到AngularJS控制器

<select id="nut"> 
         <option>---select---</option> 
         <option value="N1">N1</option> 
         <option value="N2">N2</option> 
         <option value="N3">N3</option> 
         <option value="N4">N4</option> 
</select> 
<div id="holder"></div> 
<input type="submit" value="save" ng-click="savedata()"/> 

Javascript成爲

$("#nut").change(function() { 
    val = $(this).val(); 
    var ctr = '<input type="text" name="' + val + '"/>'; 
    $('#holder').append(ctr); 
}); 

現在我想用在點擊保存按鈕的AngularJS控制器在數據庫中插入所有這些文本框的值在新行。

我知道如何通過使用data-ng-model綁定表單元素數據來爲常規表單元素執行此操作。但是當沒有時如何實現這一點。的表單元素是可變的。

我試着這樣做,

var ctr = '<input type="text" name="data.' + val + '" data-ng-model="data.' + val + '"/>'; 

<input type="submit" data-ng-click="savedata(data)"/> 

AngularJS控制器 -

.controller('testController', function ($scope, $http, $location) { 
     $scope.savedata = function (data) { 
     debugger; 
     alert($scope.data); 
     } 
}) 

但是這給數據爲未定義的值。 那還有什麼可以做的?

+0

當您的頁面加載完成後,鏈接階段結束,因此IU認爲您使用JQuery動態創建的輸入無法與Angular綁定。你可以實現你的需求,但它不會是直線和角度推薦的方式。 – davidxxx

回答

2

使用AngularJS的數據驅動方法,並從jQuery方法轉移到問題。您可以按照下面的解決方案。

讓我們先看看你的問題。

  1. 您有一份要顯示的標籤/標籤列表。由用戶輸入的
  2. 文本必須與由用戶在選擇選項選擇的標記/標籤,如果沒有從所述選擇菜單選項已被選擇
  3. 一旦不被示出
  4. 文本輸入字段相關聯用戶選擇一個標籤並輸入相應的標籤,然後按提交。您想要將數據保存到您的後端/數據庫。

讓我們爲此創建一個乾淨的解決方案。

我們將首先在這個控制器上工作,並設置我們需要的變量和模型。

angular.controller('testController',['$scope','$http','$location',function($scope,$http,$location){ 

    $scope.optionsList = ['N1','N2','N3','N4','N5']; //List of options to be displayed in select 
    $scope.selectedOption = 'Select Tags'; //Variable to store the selected option  
    $scope.textFilled = ''; //this model will store the text entered by the user 
    $scope.showTextField = false;// this model will decide when to show the text-field 

    $scope.switchTextFieldStates = function(){ 
     if($scope.selectOptions != 'Select Tags'){ 
     $scope.showTextFields = true; 
     }else { 
     $scope.showTextFields = false; 
     } 
     $scope.textFilled = ''; //This will ensure that if user changes the option then previously filled data is cleared out of the model 
    } 

    $scope.saveData = function(){ 

     console.log($scope.selectedOption,$scope.textFilled); 
//Do whatever you want to do here with the data you got 
//Reset the state of the view 
     $scope.showTextFields = false; 
     $scope.textFillled = ''; 
     $scope.selectedOptions = 'Select Tags'; 
} 

}]; 

讓我們爲這個問題創建一個合適的HTML模板。

<select ng-options="item as item in optionsList" ng-model="selectedOption" ng-change="switchTextFieldStates()"></select> 

<div id="holder" ng-show="showTextFields"><input type="text" ng-model="textFilled"/></div> 
<input type="submit" ng-click="saveData()"/> 
+0

謝謝!這很好。但是這樣一個一個地保存數據。如果我想一次保存多個文本字段的值,該怎麼辦? –

相關問題