【问题标题】:Angular js how to pass data from Ajax to select option htmlAngular js如何从Ajax传递数据以选择选项html
【发布时间】:2018-07-12 00:57:57
【问题描述】:

我是 Angular js 的新手, 当我使用 ajax 更改选择选项的 html 时遇到问题。我不确定做什么是对还是错,但我尝试的不是 UI 上的结果,也不是浏览器控制台日志中的错误,它没有效果。

这是我的 HTML

<select require="require" ng-model="getself_data" ng-change ="get_type(1)" ng-init="get_type(0)">

这是我的 js

  $scope.get_type = function(){
       $http({
         method: "POST",
         url: 'getmydata'
        }).then(success, failed);
         function success(response) {
           console.log(response);
           if(response['data']['CODE']==="000"){
             var opt_data = "";
             var total_row = response['data']['DATA'].length;

             for (var i = 0; i < total_row; i++) {
               opt_data = "<option value='" + response['data']['DATA'][i]['ID'] +"'>" +response['data']['DATA'][i]['NAME'] +"</option>";
               }
             console.log(opt_data);

             $scope.getself_data = opt_data;
           }else{
             console.log(response);
           }
         };
         function failed(response) {
             console.log(response);
             alert('Error : ' + response);
         }
}

对于来自 ajax 的结果响应是

{
   "CODE": "000",
    "DATA": [
        {
         "ID": "2",
         "NAME": "AAAA"
        },
        {
         "ID": "6",
         "NAME": "Test_name"
        }
      ]}

请帮我解决一下

【问题讨论】:

  • 在我看来,您将 ng-model 与 ng-options 混淆了
  • 您的$http 请求不应该使用GET 类型吗?事实上$http.get(url).then(...) 语法更容易理解

标签: javascript jquery html angularjs ajax


【解决方案1】:

这里的问题是您错误地生成了选择选项。

您的 get_type 函数正在将看似 html 的内容绑定到您作用域的 getself_data 模型。这更像是一种 jquery 方法,而不是 angularjs 方法。你需要让 angularjs 通过给它对象来为你生成 HTML。

相反,您需要重新编写标记,以使所有内容都保持在角度范围内。一种选择是利用 ngOptions 指令,其目的是为 元素动态生成列表 元素。您可以阅读更多关于 ngOptions 指令 here 的信息。

<select ng-model="getself_data" ng-options="option.ID as option.NAME for option in response.data"></select>

以这种方式配置标记后,您需要将 $http 调用的结果绑定到范围。由于我选择在 response.DATA 中为 option 定义我的变量,因此我们需要将 response.DATA 绑定到范围。 p>

 $scope.get_type = function(){
   $http({...}).then(success, failed);
     function success(response) {
       $scope.response = response['data'];

       //response.data will now have the two objects within your array, 
       //and therefore two option elements will be generated. One for each 
       // object within your data array. And the ID property will be bound 
       // to the option element's value property. And the label will use the 
       // NAME property.


     };
     function failed(response) {...}
}

现在通过 angularJs 中双向绑定的魔力,您的 $scope.getself_data 现在将拥有所选选项的 ID 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2022-12-05
    • 2015-11-11
    • 2023-04-08
    相关资源
    最近更新 更多