【问题标题】:ng-repeat through an Array of Objectsng-repeat 通过对象数组
【发布时间】:2016-07-05 11:30:47
【问题描述】:

我正在用 Angular JS 和 StamPlay 创建一个小喊话箱。因此,我创建了一些可以通过URL 访问的“测试呐喊”

在我的 Angular 应用中,我创建了一个服务来获取数据:

app.factory('shouts', ['$http', function ($http) {

    return $http.get('https://shoutbox.stamplayapp.com/api/cobject/v1/shouts').success(function (data) {
        return data.data;
    });

}]);

在我的 MainController 中,我将数据附加到 $scope。

app.controller('HomeController', [
    '$scope',
    'shouts',

    function ($scope, shouts) {
        $scope.shouts = shouts;
    }

]);

但是当我想通过数据 [] 进行 ng-repeat 时,我无法访问里面的对象。我不明白这是什么问题。

<div ng-repeat="shout in shouts">
  {{shout.title}}
</div>

【问题讨论】:

  • 控制台窗口中抛出任何错误?此外 - 您应该使用 track by - 来提高性能,例如ng-repeat="$index 的呐喊声中的呐喊声"
  • 不幸的是,控制台中没有错误。您可以在此处查看正在运行的应用程序:shoutbox.stamplayapp.com/#
  • 以及 HTML 和组件/指令?

标签: angularjs stamplay


【解决方案1】:

您是否忘记将控制器附加到 HTML 中?

<div ng-controller="HomeController">
    <div ng-repeat="shout in shouts">
      {{shout.title}}
    </div>
</div>

更多关于ngController的信息:https://docs.angularjs.org/api/ng/directive/ngController

【讨论】:

  • 不,我通过 $routeProvider 将控制器附加到我的视图
【解决方案2】:

即使你“返回 data.data”,shouts 也是一个 $promise。所以你需要在 promise 解决时分配 $scope.shouts。

app.factory('shouts', ['$http', function ($http) {

    return $http.get('https://shoutbox.stamplayapp.com/api/cobject/v1/shouts');

}]);

app.controller('HomeController', [
    '$scope',
    'shouts',

    function ($scope, shouts) {
       shouts.then(function(data) { $scope.shouts = data.data});
    }

]);

另一种选择是解决路由配置中的喊叫并将其注入控制器

$routeProvider
.when("/home", {
    templateUrl: "home.html",
    controller: "HomeController",
    resolve: {
        shout_data: shouts
    }


app.controller('HomeController', [
    '$scope',
    'shout_data',

    function ($scope, shout_data) {
       $scope.shouts = shout_data;
    }

]);

【讨论】:

  • 不应该是:shouts().then(function(data) { $scope.shouts = data.data});
  • {{shout.title}}
    这解决了我的问题!似乎 Stamplay 返回数据的方式有点尴尬
  • 我是在服务内部还是在 MainController 内部向我的后端添加新的喊:{}?我的意思是http post请求。
  • 为了单一责任原则,在服务中做。如果您的后端是 REST api,请考虑使用 $resource
  • 使用$resource,我又遇到了stamplay api返回数据的格式问题。 $resource.query() 似乎需要一个对象数组,但 API 返回: { "data": [], "pagination": {} } 我需要使用里面的对象来获取数据 []
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多