2016-02-25 8 views
0

ngResource в factory работает отлично, но, к сожалению, результат может выбрать индекс JSON. В то же время можно связать один и тот же $scope.resultItems переменной журналНевозможно выбрать индекс JSON при использовании ngResource на заводе

консоли выглядят следующим образом

enter image description here

Не работает с ngResource http://codepen.io/anon/pen/dMbRXx

работает отлично от переменной http://codepen.io/anon/pen/ONLgNX

var app = angular.module('app', ['ngResource']); 
 
app.controller('myCtrl', function($scope, categoryFilter) { 
 
    $scope.resultItems = categoryFilter.query(); 
 
    $scope.resultIndex = $scope.resultItems[0]; 
 
    $scope.resultIndexItem = $scope.resultItems[0].status; 
 
}); 
 
app.factory('categoryFilter', function($resource) { 
 
    return $resource("https://maps.googleapis.com/maps/api/geocode/json?address=NY", {}, { 
 
    query: { 
 
     method: "GET" 
 
    } 
 
    }); 
 
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script> 
 
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.5.0/angular-resource.min.js"></script> 
 

 
<div class="container" ng-app="app" ng-controller="myCtrl"> 
 
    <div class="col-xs-12"> 
 
    <h3>ngResource result</h3> 
 
    <pre>{{resultItems | json }}</pre> 
 
    <hr /> 
 
    <pre>{{resultIndex | json }}</pre> 
 
    <hr /> 
 
    <pre>{{resultIndexItem | json}}</pre> 
 
    </div> 
 
</div>

ответ

1

Каждый ресурс на самом деле является ajax-запросом, что означает, что он асинхронный, поэтому вы должны использовать обратные вызовы для функции query. Тогда ваш код выглядит следующим образом

var app = angular.module('app', ['ngResource']); 
app.controller('myCtrl', function($scope, categoryFilter) { 
    categoryFilter.query(function(results){ 
    $scope.resultItems = results; 
    $scope.resultItems.results[0]; 
$scope.resultIndexItem = $scope.resultItems.status; 
    });  
}); 
app.factory('categoryFilter', function($resource) { 
    return $resource("https://maps.googleapis.com/maps/api/geocode/json?address=NY", {}, { 
    query: { 
     method: "GET" 
    } 
    }); 
}); 

link

Update

К сожалению, если я пропущу прочитать вам вопрос, все детали в формате JSON в {} будет объект можно получить с помощью ., для пример в json results и status - это объект, а элементы, представленные в [], представляют собой массив и к ним можно получить доступ с помощью индекса.

От json enter image description here enter image description here

+0

Вопрос заключается в том, что выбрать JSon индекс, например '$ scope.resultItems [0]' или '$ scope.resultItems [0] .status' – Muhammed

+0

@MuhammedAthimannil Я обновил мой ответ. – Sanoob