2016-12-10 1 views
0

저는 Angular의 초보자입니다. 나는 쉬운 질문이라고 생각한다. 내 서버에 호스팅 된 다른 객체를 포함하는 json 파일이 있습니다. 각 객체에 대한 목록을 표시했습니다. 이제 각 목록 항목 (개체)을 클릭하면 세부보기 (목록보기와 다름)에서 각 항목의 세부 정보를 표시하려고합니다. 매개 변수 (id)를 사용하여 세부 뷰로 리디렉션하는 방법을 알고 있지만 해당 특정 개체의 세부 정보를 렌더링하는 방법을 알지 못합니다. 여기 나는 내 코드를 보여Angular js - 내 서버에있는 json 파일에서 부분 데이터를 추출하여 매개 변수를 전달하는 상세 뷰를 얻는 방법?

data.json

[ 
{ 
"id": "1", 
"name": "james", 
"age": "20", 
"city": "NY" 
}, 
{ 
"id": "2", 
"name": "allan", 
"age": "21", 
"city": "London" 
}, 
{ 
"id": "3", 
"name": "thomas", 
"age": "22", 
"city": "Belfast" 
} 
] 

app.js

angular.module("myApp", ["controllers", "services", "directives", "ngRoute"]); 
angular.module("myApp").config(function($routeProvider) { 
$routeProvider 
    .when('/', { 
     templateUrl : 'templates/home.html', 
     controller : 'HomeCtrl' 
    }) 
    .when('/list', { 
     templateUrl : 'templates/list.html', 
     controller : 'ListCtrl' 
    }) 
    .when('/list/:id', { 
     templateUrl: 'templates/item.html', 
     controller: 'ItemCtrl' 
    }) 
    .otherwise({redirectTo: '/'}); 
}); 

controllers.js

... 
.controller('ListCtrl',function($scope, MyService) { 
$scope.list = {}; 
MyService.getData() 
    .then(function(result) {         
      $scope.list=result.data; 
      }) 
    .catch(function(error) { 
      console.log('There is an error.', error); 
      }); 
}) 
.controller('ItemCtrl',function($scope, $routeParams, MyService, $location) { 
var id = $scope.id = $routeParams.id; 
$scope.item = {}; 
MyService.getData() 
    .then(function(result) { 
      $scope.item=result.data; 
       if(id) { 
        return result.data[id] 
       } 
      }) 
    .catch(function(error) { 
      console.log('There is an error.', error); 
      }); 
}) 

service.js을

... 
.factory('MyService', function($http) {  
return { getData: getData }; 
function getData() { 
    return $http.get('data.json'); 
} 
}) 

<div ng-controller="ItemCtrl"> 
    <p>{{item.name}}</p> 
    <p>{{item.city}}</p> 
</div> 

어떤 제안

을 item.html?

미리 감사드립니다.

답변

0

개체 목록을 서비스와 함께로드 할 수 있으며 서비스 내 변수에 저장할 수 있으므로 매번 서비스를 호출하지 않아도됩니다 (json 파일을 가져 오기 위해). 최신 데이터는 매번 업데이트됩니다. 당신이

... 
.factory('MyService', function($http, $q, $filter) {  

    var itemList = []; 
    var self = {}; 

    self.getList = getList; 
    self.getItem = getItem; 

    return self; 

    function getList(){ 
     var defer = $q.defer(); 

     $http.get('data.json').then(function(response){ 
      itemList = response.data; 
      defer.resolve(itemList); // you can do data manipulation here if you need to 
     },function(error){ 
      defer.reject(error); //you can customize your error 
     }); 

     return defer.promise; 
    } 

    function getItem(itemId){ 
     if(itemList){ 
      var found = $filter('filter')(itemList, {id:itemId}, true); 

      return found[0]; //the [0] is to get the first item since found is an array 
     } 
    } 
}) 

당신은 전에 목록 컨트롤러의 데이터 (항목)로드 할 수 있습니다 할 수있는 서비스에 https://plnkr.co/edit/1k3RhxIWnsdY7rPViRhK?p=preview

:

당신이 코드에 문제가있는 경우

아래 plunkr을 확인 컨트롤러가 경로에로드됩니다. 컨트롤러에 "항목"을 주입해야합니다.

angular.module("myApp").config(function($routeProvider) { 
    $routeProvider 
     .when('/list', { 
     templateUrl: 'templates/list.html', 
     controller: 'ListCtrl', 
     resolve: { 
      items: function(MyService){ 
       MyService.getList().then(function(response){ 
        return response 
       }); 
      } 
     } 
    }) 
    . 
    ...Other Routes Here... 
    .otherwise({redirectTo: '/'}); 

});

지금 당신의 품목 컨트롤러에서 당신은 btinoco, 당신의 빠른 대답이

.controller('ItemCtrl',function($scope, $routeParams, MyService) { 
    var id = $routeParams.id; 

    $scope.item = MyService.getItem(id); 

}) 
+0

감사 할 수 있습니다. 유감스럽게도 오류가 발생했습니다 : 오류가 있습니다. TypeError : defer.resolve가 함수가 아닙니다 (...) 그리고 항목 목록도 나타나지 않습니다. 확실히 JSBin이 도움이 될 수 있습니다. – Dubliner

+0

좋아, 내가 jsbin에서 일하고있다 – btinoco

+0

멋지다! 노력해 주셔서 감사합니다. – Dubliner

관련 문제