绑定ng-options和ng-model的问题

时间:2015-12-04 00:20:52

标签: html angularjs angular-ngmodel ng-options

我有一个网络应用程序,前端接收两个字段的用户输入:日期和类别,输入必须作为JSON发送到后端。我无法这样做。

我的代码如下:

的index.html

<div ng-controller="HomeController">
<p>Day of publishing the article:</p>
<select name="day" id="day" ng-options="day as day.name for day in days" chosen ng-model="formData.day"></select><br><br>
</div>

<div ng-controller="HomeController">
<p>Category of the article:</p>
<select name="category" id="category" ng-options="category as category.name for category in categories" chosen ng-model="formData.category"> </select><br><br>
</div>

HomeController.js

var myApp = angular.module('myApp.controllers',[]);

myApp.controller('HomeController', ['$scope','$http',function ($scope,$http) {

    console.log("Hello");
    $scope.formData={};

    $scope.days = [
     { name: 'Monday' },
     { name: 'Tuesday' },
     { name: 'Wednesday' },
     { name: 'Thursday' },
     { name: 'Friday' },
     { name: 'Saturday' },
     { name: 'Sunday' },
   ];    
    $scope.categories = [
     { name: 'Lifestyle' },
     { name: 'Entertainment' },
     { name: 'Business' },
     { name: 'Social Media' },
     { name: 'Tech' },
     { name: 'World' },
   ];   

    $scope.submit = function() {

        $http.post("http://localhost:8080/api/users/", $scope.formData).
        success(
            function(response) {
                console.log(response);
            })
        .error(function(){
            console.log("Error");
        });
    }
}]);

Front-end sample

Sample output

1 个答案:

答案 0 :(得分:0)

选择下拉列表包含在HomeController的不同实例中。因此,下拉列表中的formData模型属于不同的范围。我已将两个下拉列表包装在HomeController的单个实例中。

<div ng-controller="HomeController">
   <p>Day of publishing the article:</p>
   <select name="day" id="day" ng-options="day as day.name for day in days" chosen ng-model="formData.day"></select><br><br>

   <p>Category of the article:</p>
   <select name="category" id="category" ng-options="category as category.name for category in categories" chosen ng-model="formData.category"> </select><br><br>
</div>

这是一个有效的fiddle