2016-11-29 80 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

谢谢!这很好。但是这样一个一个地保存数据。如果我想一次保存多个文本字段的值,该怎么办? –

相关问题