Angular JS:将表单选择选项值传递给数据库不起作用

时间:2016-04-23 17:12:53

标签: angularjs

我目前有一张带有<select>的表单和以下选项。我正在尝试将值传递到我的数据库中,但是当运行应用程序类别时,将显示为未定义。表单使用ng-controller =&#34; eventCtrl&#34;

表格选择下面的代码。

<div class="input-field col s5">
 <select class="browser-default">
  <option value="" disabled selected>Choose your category</option>
  <option value="Mountain" ng-model="category">Mountain</option>
  <option value="Forest" ng-model="category">Forest</option>
  <option value="Beach & Sea" ng-model="category">Beach & Sea</option>
  <option value="Fresh Water" ng-model="category">Fresh Water</option>
  <option value="Aero" ng-model="category">Aero</option>
  <option value="Desert" ng-model="category">Desert</option>
 </select>
</div>

下面的eventCtrl代码。

angular.module('socialApp')
 .controller('eventCtrl', function($scope, $http) {
  $scope.createEvent = function() {
   $http.post('/events/createEvent', {
    title: $scope.title,
    category: $scope.category,
    city: $scope.city,
    state: $scope.state,
    date: $scope.date,
    time: $scope.time,
    description: $scope.description
  })
  .then(function(result) {
    console.log(result.data.status);
    console.log(result);
  })
 };
});

我很失落,请帮忙!

2 个答案:

答案 0 :(得分:5)

ng-model属性应位于select元素而不是每个option元素上,如下所示:

<div class="input-field col s5">
 <select class="browser-default" ng-model="category">
  <option value="" disabled selected>Choose your category</option>
  <option value="Mountain">Mountain</option>
  <option value="Forest">Forest</option>
  <option value="Beach & Sea">Beach & Sea</option>
  <option value="Fresh Water">Fresh Water</option>
  <option value="Aero">Aero</option>
  <option value="Desert">Desert</option>
 </select>
</div>

我绝对会在documentation上查找,因为它非常详细!

答案 1 :(得分:0)

考虑使用这样的ngOptions:

<select ng-model="category" 
        ng-options="obj as obj.name for obj in arrayOfObject" />
  

a as b语法允许您将a绑定到模型,同时为下拉标签显示b。

如果您需要获取更改后的值,请使用ng-change="getSelectedValue(category)"