2015-10-20 48 views
0

HTML表單代碼想要得到的表單元素的值在AngularJS陣列

<form ng-submit="mysubmit()" ng-controller="question_post" > 
    <textarea name="question" id="question" ng-model="question"></texarea> 
    <input type="text" name="opt[]" ng-model="opt[]" /> 
    <input type="text" name="opt[]" ng-model="opt[]" /> 
</form> 

角JS代碼

var obj = angular.module('root', []); 

obj.controller('question_post', ['$scope','$http', function ($scope,$http) { 
    $scope.mysubmit = function(){ 
    $http({ 
     url: "some_url", 
     method: "POST", 
     headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
    data:$.param({user_id:1,'question':$scope.question,'option':$scope.opt}) 
      }).success(function(data, status, headers, config) { 
      console.log(data); 
       alert(data); 
       $scope.data = data; 
      }).error(function(data, status, headers, config) { 
       $scope.status = status; 
     }); 
     } 
    }]); 

上面將返回錯誤代碼的時候我寫ng-model="opt[]"ng-model="opt"返回一個值。

我想添加名稱爲opt的動態文本字段,爲此我想獲取數組中的opt值。 如果我使用PHP然後它好吧($option =$_POST['opt'])但我怎麼能得到在AngularJS中的數組值opt

回答

0

您可以在控制器中定義選項,將它傳遞給視圖並使用ng-repeat來遍歷選項。這樣你可以使用$index並將你的選項保存到一個數組中。以Plunker爲例。

所以基本上你遍歷你的選擇,因爲提到:

<div ng-repeat="option in vm.options"> 
    <input type="text" name="{{ option.name }}" ng-model="vm.opt[$index]" /> 

正如你可以看到我用ng-model這樣的:

ng-model="vm.opt[$index]" 

這將保存在一個輸入字段的值數組在$index的位置,這非常類似於for循環中的迭代器,並且從0開始。

相關問題