简体   繁体   English

如何使用内部请求回调函数中的angular创建表

[英]How to create table using angular from inside request callback function

I'm trying to create a table using angular. 我正在尝试使用angular创建一个表。 The problem is that I need to create that table based on JSON response from my http request (at which point I call the responseHandler function below: 问题是我需要根据我的http请求中的JSON响应创建该表(此时我将调用responseHandler函数:

function call(){
    $.ajax({
        url: url
        , type: "GET"
        , success: function (response, status, xhr) {

            responseHandler(response);
        }
        , error: function (xhr, status, error) {}
    });
}

 function responseHandler(response) {
    var data = angular.fromJson(response);
    var user = angular.fromJson(data['users']);
    userdata = user['data'];// this is correctly assigning the data I 
                                // need to the variable userdata
    var tApp = angular.module('tApp', []);
    tApp.controller('tCtrl', ['$scope', function ($scope) {

        $scope.userdata = userdata;
        $("#usertable").css("visibility", "visible");
    }]);
 }

Here is my html: 这是我的HTML:

<div ng-app="tApp" ng-controller="tCtrl" class="tab-content clearfix" id='tCtrl'>
<table id='usertable' border="1">
                        <tr ng-repeat="x in userdata">
                            <td>{{x.name}}</td>
                            <td>{{x.id}}</td>
                            <td>{{x.picture.data.url}}</td>
                        </tr>
                    </table>
</div>

I keep getting the angular.js:14516 Error: [$controller:ctrlreg] error. 我一直得到angular.js:14516错误:[$ controller:ctrlreg]错误。 So it seems my controller is not being recognize by angular. 所以看起来我的控制器没有被角度识别。 Any ideas? 有任何想法吗?

Thank you! 谢谢!

Looks like your angular module and controller are declared only on success. 看起来您的角度模块和控制器在成功时声明。 But you are using ng-controller in your view. 但是您在视图中使用ng-controller So if the request fails, you're in trouble :) 所以,如果请求失败,你就麻烦了:)

When AngularJS sees an ng-controller directive, but cannot find the matching controller, it throws that error. AngularJS看到ng-controller指令但找不到匹配的控制器时,它会抛出该错误。 Here is more info on the error 以下是有关错误的更多信息

But in general, there are issues with your code: 但总的来说,您的代码存在问题:

  1. you should use angular's $http module to make http calls. 你应该使用angular's $http模块进行http调用。 You should not use jquery because it will not trigger a digest cycle once a response is received and angular will not know anything about the api call. 您不应该使用jquery因为一旦收到响应它就不会触发摘要周期,而angular将不知道有关api调用的任何信息。

  2. you should not create your angular module inside another function, just create it globally 你不应该在另一个函数中创建角度模块,只需在全局创建它

If you are using angular, you should completely stop using JQuery, the asynchronous ajax call will mess up your application really hard because of angular's digest loop. 如果你正在使用angular,你应该完全停止使用JQuery,异步ajax调用会因为angular的摘要循环而非常困难你的应用程序。

It's also a best practice to split the data-fetching into a different service, as it sometimes gets messy really fast and pollutes the controllers with a lot of code without application logic. 将数据获取分成不同的服务也是一种最佳实践,因为它有时会非常快速地混乱并且在没有应用程序逻辑的情况下使用大量代码污染控制器。

And because you don't use JQuery, you don't need to place ID in elements. 而且因为您不使用JQuery,所以您不需要在元素中放置ID。

HTML: HTML:

<div ng-app="tApp" ng-controller="tCtrl" class="tab-content clearfix">
  <table border="1" ng-show="userdata.length > 0">
    <tr ng-repeat="x in userdata">
      <td>{{x.name}}</td>
      <td>{{x.id}}</td>
      <td>{{x.picture.data.url}}</td>
    </tr>
  </table>
</div>

Javascript 使用Javascript

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

tApp.factory('dataFetchingService', ['$http', function ($http) {
  return {
    getUserData: function() {
      $http.get('/someUrl/to/userData')
        .then(
          response => response.data,
          error => console.error(error)
        );
    }
  };
}]);

tApp.controller('tCtrl', ['$scope', 'dataFetchingService', function ($scope, dataFetchingService) {
    $scope.userdata = [];

    dataFetchingService.getUserData().then(userData => {
      $scope.userdata = userData;
    });
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM