我想将选择框的ID传递给Angular JS中的函数

时间:2017-04-06 07:34:10

标签: javascript angularjs

我有以下选择框

<select class="form-control" ng-model="community_type_id">
<option ng-repeat="x in myData" value="{{ x.community_type_id }}" ng-click="sendID(x.community_type_details)">{{ x.community_type_details }}</option>
</select>

我想将x.community_type_id传递给像这样的函数sendID。但不适用于我的情况。

var app = angular.module('EntityApp', []);
app.controller('EntityAppCntroller', function($scope, $http) {
    $http.get("http://122.322.5.459:8080/apartment/community/type/list").then(function(response) {
        $scope.myData = response.data.type;
    });
    $scope.sendID = function(id) {
        alert(id);
        $http.get("http://11.22.33.44:8080/apartment/community/sub/type/list/" + id).then(function(response) {
            $scope.myDatas = response.data.type;
        });
    }
});

3 个答案:

答案 0 :(得分:1)

您需要更改html以进行选择,并且必须提供ng-model。 然后就没有必要传递任何id。

喜欢:

 <select ng-model="Selected" 
  ng-options="x as x.community_type_details for x in myData" 
  ng-change="sendID()">
</select>

然后在控制器中:

$scope.sendID = function() {
alert($scope.Selected.community_type_details);
alert($scope.Selected.community_type_id);
}

见工作Fiddle.

答案 1 :(得分:0)

angular.module('app', []).controller('MyController', ['$scope', function($scope) {
    $scope.myData = [
         {community_type_id:1, community_type_details:'details1'},
         {community_type_id:2, community_type_details:'details2'},
         {community_type_id:3, community_type_details:'details3'},
      ];
    $scope.sendID = function(){
      $scope.id = $scope.myData.find(function(x){
        return x.community_type_id == $scope.community_type_id;
      }).community_type_details;
      console.log('sendID with ' + $scope.id + ' called');
    }      
}]);
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<body ng-app="app">
  <div ng-controller="MyController">
    <select class="form-control" ng-model="community_type_id" ng-change="sendID()">
      <option ng-repeat="x in myData" value="{{ x.community_type_id }}">{{ x.community_type_details }}</option>
    </select>
    <p>community_type_id: {{community_type_id}}</p>
    <p>id: {{id}}</p>
  </div>
</body>

答案 2 :(得分:0)

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

 myApp.controller("myController", function($scope){
  
 
  
  $scope.list= [
    { id:1,name:'Ajay'},
    { id:2,name:'jay'},
    { id:3,name:'ay'},
    { id:4,name:'y'},
    { id:1,name:'Ajay'}];
  
$scope.hasChanged = function(selectedID){
 alert(selectedID)
}  
  

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


  <body ng-app="myApp">
    
    <div ng-controller= "myController">
  
    
    <select ng-options="item.name for item in list" 
            ng-model="selected"
            ng-change="hasChanged(selected.id)">
  </select>
    
    
    </div>
    
   
  </body>