2013-08-21 2 views
1

현재 내 각진 앱의 다른 곳에 테이블을 채우는 다음 서비스가 있습니다.

업데이트 :

'use strict'; 

    angular.module('projyApp') 
     .service('data', function data() { 
     // AngularJS will instantiate a singleton by calling "new" on this function    

      var getAllPeeps = function() { 
       return peeps; 
      } 

      var insertPeep = function(peep) { 
       peeps.push(peep); 
      } 
      var getPeep = function(peep) { 
       var foundPeep; 
       if (peep.firstname) { 
        peeps.forEach(function (pps){ 
         if (pps.firstname == peep.firstname) { 
          foundPeep = pps; 
         } 
        }); 
       } else if (peep.lastname) { 
        peeps.forEach(function (pps){ 
         if (pps.lastname == peep.lastname) { 
          foundPeep = pps; 
         } 
        }); 
       } else if (peep.inumber) { 
        peeps.forEach(function (pps) { 
         if (pps.inumber == peep.tagid) { 
          foundPeep = pps; 
         } 
        }); 
       } 

       if (foundPeep) { 
        return foundPeep; 
       } else { 
        return "Error"; 
       } 
      } 

      var getDataFromServer = function() { 
       //Fake it. 
       var peeps = [ 
        {firstname:'Buster', lastname:'Bluth', tagid:'01'}, 
        {firstname:'John', lastname:'McClane', tagid:'02'}, 
        {firstname:'Mister', lastname:'Spock', tagid:'03'} 
       ]; 

       return peeps; 
      } 

      var peeps = getDataFromServer(); 

      return { 
       getAllPeeps : getAllPeeps, 
       insertPeep : insertPeep, 
       getPeep : getPeep 
      } 
     }); 

은 분명히이 작품, 그러나 나는 '친구들'배열이 외부 JSON 파일에서 개체를 개최하고자합니다. 과 같이 외부 JSON 파일에서 '친구들'을로드하는 동안 나는 기능을 유지할 수있는 방법

:

$http.get("../../TestData/peeps.json").success(function(data) { 

      }); 

답변

1

각도는 가서 얻을 바인딩이 방법을 수행합니다. 그래서 만약 당신이 가지고 있으면

$scope.var = function() { 
$http.get(blah).success($scope.peeps = data.peeps;); 
}; 

당신의 전망에 $ scope.peeps를 업데이트 할 것입니다. $ scope.var은 일반적으로 버튼입니다.

+0

콘솔에 "오류 : 알 수없는 공급자 : $ scopeProvider <- $ scope <- 데이터"가 표시됩니까? – captainrad

+2

$ scope를 서비스에 삽입해야합니다. –

+0

내 코드를 더 많이 포함하도록 업데이트했습니다. – captainrad

0

일반적으로 나는 $ http promise를 반환합니다. 그리고 서비스의 발신자는 성공을 통해 원하는 모든 것을 할 수 있습니다. 그러나 이전 버전과의 Compability가를 유지하기 위해, 당신이 시도 할 수 있습니다 :

var getDataFromServer = function() { 
     var peeps = []; 
     $http.get("../../TestData/peeps.json").success(function(data) { 
      peeps.push.apply(peeps,data); 
     }); 

     return peeps; 
    } 

그래서 당신이 처음에 빈 배열을 반환합니다. 하지만 json 배열로 채워질 것입니다.

0
function myController($scope, $http){ 
    $http.get(url).success(function(data){ $scope.people = data; }); 
}