【问题标题】:How to deal with JSON response in Angular如何在 Angular 中处理 JSON 响应
【发布时间】:2015-05-12 01:24:12
【问题描述】:

我有以下控制器:

function EntryCtrl($scope, Restangular){
 console.log("*** EntryCtrl");
 $scope.roles= Restangular.all("roles").getList();
 console.log("*** EntryCtrl: " +  JSON.stringify($scope.roles));
}

控制台输出为:

*** EntryCtrl: {"restangularCollection":true} 

当我使用休息浏览器插件进行相同的休息调用时,我得到:

[
 {
     "name": "dev"
 }
]

我不知道如何让 Angular 处理与其他浏览器插件相同的响应。 我的最终目标是在 Angular 中获得角色名称“dev”。 在 Angular 页面上,我想在使用角色名称的链接上使用“ng-show”,如下所示:

<a href="" ng-show="roles.contains('')>Foo</a>

【问题讨论】:

    标签: javascript json angularjs


    【解决方案1】:

    试试

    $scope.roles= Restangular.all("roles").getList().$object;
    

    来自doc

    是否对 /accounts 进行 GET 默认情况下返回一个空数组。一旦从服务器返回一个值 该数组充满了这些值。所以你可以在你的模板中使用它

    $scope.accounts = Restangular.all('accounts').getList().$object;
    

    【讨论】:

      【解决方案2】:

      根据文档:

      Restangular 使用承诺。而不是像 $resource 那样对对象进行“魔法”填充

      所以要从服务器获取响应,你必须像这样使用 .then 回调:

      Restangular.all("roles").getList().then(function(response){
          $scope.roles = response;
      });
      

      在你的模板中:

      <li ng-repeat="role in roles">{{role.name}}</li>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-28
        • 2011-08-10
        • 1970-01-01
        • 2013-05-09
        • 2017-02-14
        • 1970-01-01
        相关资源
        最近更新 更多