我无法访问所选选项的值,我认为在为选择菜单或类似菜单提供ng-model时犯了一个错误。

(HTML)选择选项

<select id="countryListId"></select>


(AngularJS控制器)

        $scope.fetchCountries = function() {

        var $selectCountry = $('#countryListId');

        $.ajax( {
            url: 'http://.../someurl/dropdown?typ=Countries',
            dataType: 'JSON',
            success: function(data) {

                $selectCountry.html('<select ng-model="locationForm.country"></select>');
                $.each(data, function(key, val) {
                    $selectCountry.append('<option value="' + val.code + '">' + val.value + '</option>');
                })
            }, error: function() {
                $selectCountry.html('<option id="-1">none available</option>');
            }
        });

    }


该代码工作正常,并向我显示了从URL提取的数据的填充下拉列表,但是:


  当我选择一个选项并尝试通过ng-model访问选定的值时:
  我得到空


因此,我希望您能指导我通过Ajax或其他任何可以获取所选选项的方法提供ng-model的正确方法。

最佳答案

使用数组(在本例中为$scope.dataselect =[])将保留从API提取的数据。并将其绑定到模板选项元素,如下所示:

<select ng-model="locationForm.country">
   <option ng-repeat="data in dataselect" value="{{data.code}}">{{data.value}}</option>
</select>


在控制器上,将数据设置或推送到成功回调中当前作用域上的数组($ scope.dataselect)。如果数据更改,则视图将自动更新。您无需手动更新视图。您也可以使用$http服务。

app.controller('myCtrl', function($scope, $http) {
  $scope.fetchCountries = function() {
    $scope.dataselect = []; // something [{code:"1",value:"data1"},{code:"2",value:"data2"}]
    $http.get("http://.../someurl/dropdown?typ=Countries")
    .then(function(data) {
       angular.forEach(data, function(val, key) {
        var elem = {key:val.code,value:val.value};
        $scope.dataselect.push(elem);
       })
    }, function(response) {
        //handles error
        $scope.dataselect = [{code:"-1",value:"Not available"}]
    });
  });
});




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

app.controller('MainCtrl', function($scope,$http) {
 $scope.dataselect =[];
 $scope.update = function() {
  console.log("changed "+$scope.locationForm.country);
}
 $scope.fetchCountries = function() {

  $scope.dataselect =[];
  $scope.dataraw ={"code1":"value1","code2":"value2"}; //dummy from API
   angular.forEach($scope.dataraw, function(val, key) {

     var elem = {key:key,value:val};

     $scope.dataselect.push(elem);
   })
 }



});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl ">
    {{locationForm.country}}
  <select  ng-change="update()" id="countryListId" ng-model="locationForm.country">
    <option ng-repeat="data in dataselect" value="{{data.key}}">{{data.value}}</option>
  </select>
  <button ng-click="fetchCountries()">Fetch</button>
</div>







解决方案2 :(为便于说明)

但是,如果只想使用jQuery#html函数,则应按如下所示创建wrapper元素:

<div id="select-container-js">
    <select id="countryListId"></select>
</div>


现在您可以使用它了。但是在这种情况下,您还需要调用$compile来用新元素编译DOM并将其链接到当前作用域。

$('#select-container-js').html('<select  id="countryListId" ng-model="locationForm.country"></select>');
//you should set $selectCountry just before using it because of reference losing.
var $selectCountry = $('#countryListId');
$.each(data, function(key, val) {
  $selectCountry.append('<option value="' + val.code + '">' + val.value + '</option>');
})
$compile($selectCountry)($scope);


不是:不要忘记将$ compile服务注入到控制器中。

app.controller('MainCtrl', function($scope,$compile) {}

关于javascript - 如何在AngularJS中通过AJAX添加ng-model,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48223578/

10-12 12:28
查看更多