【问题标题】:Angular loading data from server json从服务器 json 角度加载数据
【发布时间】:2016-03-11 19:23:22
【问题描述】:

谁能告诉我在 ng repeat 中使用 jsonObjects 的最佳解决方案是什么? 我的代码如下:

我的 PHP 响应是这样的:

die(json_encode(array('sts'=>'success', 'title'=>'*****', 'msg'=>'*******', 'data'=>$result)));

我的angular.js服务是这样的:

LeadApp.service('LeadsService', function ($http) {
  var AllLeads = {
    async: function() {
        var promise = $http({
            url: '../app/ServerData.php',
            method: "POST",
            params: { req_id: 'leads' }
        }).then(function (response) {
        return response.data;
      });
      return promise;
    }
  };
  return AllLeads;
});

然后在我的控制器中,我调用该服务并设置一个lead var,以便在我的视图中使用 ng repeat:我已经保证正在加载我的数据。我从下面附上了控制台日志的图片。但不知何故,ng重复不会像预期的那样工作......我做错了什么?没有错误!

    ....
        LeadsService.async().then(function (d) {
                this.leads = d.data;
                console.log(this.leads);
       this.list_all = this.leads;

这是视图中主要的 ng 重复部分(自定义 ng 重复与“dir-paginate”): ...

<div class="widget-content leads_list" ng-controller="leadsController as leads">
<tr dir-paginate="lead in leads.list_all | orderBy:sortKey:reverse | filter:search | itemsPerPage:15" pagination-id="leads.list_all">
    <td scope="row">{{lead.id}}</td>

...

【问题讨论】:

  • 您的 ng-repeat 代码在哪里?您可以发布 ng-repeat 部分吗?

标签: javascript php angularjs json


【解决方案1】:

您需要在then 方法之外绑定this 上下文。

由于您使用的是ng-controller="leadsController as leads",因此最好绑定到变量leads

var leads = this;
LeadsService.async().then(function (d) {
        leads.list_all = d.data;
        console.log(leads.list_all);
});

then 方法内部的this 上下文与then 方法外部的this 上下文不同。还绑定到您在模板中使用的相同名称有助于避免混淆。

【讨论】:

    【解决方案2】:

    this 不是该回调函数上下文中的控制器。所以你需要将this分配给控制器中的一个变量。

     var ctrl = this;
    
     LeadsService.async().then(function (d) {
            ctrl.leads = d.data;
            console.log(ctrl.leads);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多