2013-08-21 30 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

角度做2路从一开始走的结合。所以,如果你有一个

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

它会更新您的视图上的$ scope.peeps。 $ scope.var通常是一个按钮。

+0

控制台给我“Error:Unknown provider:$ scopeProvider < - $ scope < - data”? – captainrad

+2

您必须向服务中注入$ scope。 –

+0

我已经做了更新以包含更多我的代码。 – captainrad

0

通常我会以角度返回$ http promise。而来自服务的来电者可以使用成功来做任何事情。 但要保持向后相容表象,你可以试试这个:

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; }); 
}