簡體   English   中英

動態創建選擇框並賦值

[英]Dynamically create Select boxes and assign values

在 angular app.js 中,我在具有唯一 ID 的表單中動態放置多個選擇框。 如何獲取在控制器內的那些選擇框中選擇的值。

添加了一個變量

$scope.sibling_type = {};

用於加載選擇框的 Javascript 代碼。

$scope.linkSiblingFinish = function(sibling){
   var str_siblingtype = "<div class='col-sm-2' style='margin-bottom:15px'>" +
     "<select ng-model='sibling_type[" + sibling.id + "]' class='form-control' id='sibling_type_"+sibling.id+"'>" +
       "<option class='ng-binding ng-scope' value='1'>Sister->Brother</option>" +
       "<option class='ng-binding ng-scope' value='2'>Brother->Sister</option>" +
       "<option class='ng-binding ng-scope' value='3'>Sister->Sister</option>" +
       "<option class='ng-binding ng-scope' value='4'>Brother->Brother</option>" +
     "</select></div>";

    document.getElementById('div_siblings').innerHTML = str_siblingtype;
}

上面的腳本將在單擊按鈕時調用,變量 'sibling' 將每次加載不同的 'id'。 假設它被調用了 2 次,id 為“23”和“24”。 將有 2 個選擇框作為“sibling_type_23”和“sibling_type_24”。

在提交按鈕上

$scope.saveSibling = function(data){
    dataFactory.httpRequest('index.php/students/sibling/'+$scope.form.id,'POST',{},$scope.form).then(function(data) {
    });
}

我如何綁定/分配選項值,以便在提交表單時我可以在 Laravel 控制器內的那些選擇框中獲取所選選項。

您可以為此使用不同的方法:

  1. 在您的控制器中創建一個新的“sibling_type”范圍。

     $scope.sibling_type = {};
  2. 接下來,更新linkSiblingFinish所有動態選擇的ng-model ,例如:

     "<select ng-model='sibling_type[" + sibling.id + "]' class='form-control' id='sibling_type_"+sibling.id+"'>" +
  3. 現在,提交表單后,您可以在這些選擇框中獲得所選選項。 喜歡:

     var sibling_type_23 = $scope.sibling_type['23']; var sibling_type_24 = $scope.sibling_type['24'];

演示:

 const app = angular.module('myApp', []); app.controller('AppCtrl', function ($scope) { $scope.siblings = [{id: 23,name: 'Sibling 23'},{id: 24,name: 'Sibling 24'}]; $scope.sibling_type = {}; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="AppCtrl"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr ng-repeat="sibling in siblings"> <td>{{sibling.name}}:</td> <td><input type="text" ng-model="sibling_type[sibling.id]" placeholder='Type here..' /></td> </tr> </table> <pre>{{sibling_type | json }}</pre> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM