在select选项中获取所选项的id并将其发送到URL

时间:2015-10-26 01:02:36

标签: angularjs

我在将选定项目的ID从选择输入发送到我的休息服务时遇到问题,我有两个控制器,第一个显示所有类:

.controller("classNameCtrl", ["$scope", "$http",function ($scope, $http) {

    $http({method: 'GET', url: 'URL/Classes'})

       .success(function (data) {
           $scope.posts = data; // response data  
           $scope.countSelected = $scope.posts[0].Id;    
           console.log('Selected count ID: ' + $scope.countSelected);
           console.log("success");
        })

        .error(function (data, status, headers, config) {
           console.log("data error ...");
                            });

        $scope.onchange = function(id) {
        console.log("id:"+$scope.countSelected);
           } }])

和我从选择输入中获取所选项目ID的控制器:

.controller("etudajoutCtrl", ["$scope", "$http", function ($scope, $http) {
        $scope.listetud = function () {

          $http({method: 'POST',
          url:'URL/Students/ajout' ,
          data:'{"FirstName":"tomy","ClassId": "'+$scope.countSelected+'"}'})
          .success(function (data) {
            console.log("success");
             }).error(function (data, status, headers, config) {
            console.log("data error ...");
             });}
    }])

这是我的HTML代码:

    <div ng-controller="classNameCtrl">
        <select>
            <option ng-model="countSelected" ng-change="onchange(posts[countSelected-1])" ng-repeat="post in posts" >{{post.Libel}}</option>
        </select>
    </div>  
</section>  

这是我在加载页面时以及为select输入选择其他项目时总是得到的结果:

Selected count ID: 1
app.js:2335 success

非常感谢你的帮助

2 个答案:

答案 0 :(得分:1)

您的HTML应使用ng-model进行整个选择。您无法在ng-model中多次使用<option>指令,因为它无法正确绑定。

另外,将value属性设置为一个数字,以便countselected为数字。

使用数字的最佳方法是使用$index

进行迭代
<div ng-controller="classNameCtrl">
    <select ng-model="countSelected" ng-change="onchange(posts[countSelected-1])">
        <option ng-repeat="post in posts track by $index" value="{{$index}}" >{{post.Libel}}</option>
    </select>
</div>  

来源:https://docs.angularjs.org/api/ng/directive/select

答案 1 :(得分:1)

虽然我认为使用$ index作为值是一种很棒的方式,但我建议在这种情况下使用内置的ng-options

假设数据结构:

&#13;
&#13;
angular.module('test', [])

.controller('Test', function($scope) {
  $scope.posts = [{
    Id: 1,
    Libel: 'one'
  }, {
    Id: 2,
    Libel: 'two'
  }, {
    Id: 3,
    Libel: 'three'
  }]
  
  // $scope.countSelected = 2; // add this if you need to pre-select
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>

<div ng-app='test' ng-controller='Test'>
  <select ng-model="countSelected" ng-options="post.Id as post.Libel for post in posts" ng-change="onchange(countSelected)"></select>
</div>
&#13;
&#13;
&#13;