$http.get以加载外部json
目前,我有以下服务,在我的angular应用程序的其他地方填充一个表 更新:$http.get以加载外部json,json,angularjs,Json,Angularjs,目前,我有以下服务,在我的angular应用程序的其他地方填充一个表 更新: 'use strict'; angular.module('projyApp') .service('data', function data() { // AngularJS will instantiate a singleton by calling "new" on this function var getAllPeep
'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
}
});
显然这是可行的,但是我希望“peeps”数组保存来自外部json文件的对象
如何在从外部json文件加载“peeps”时维护功能,如下所示:
$http.get("../../TestData/peeps.json").success(function(data) {
});
Angular从一开始就进行双向绑定。所以如果你有
$scope.var = function() {
$http.get(blah).success($scope.peeps = data.peeps;);
};
它将更新视图上的$scope.peeps$scope.var通常是一个按钮 Angular从一开始就进行双向绑定。所以如果你有
$scope.var = function() {
$http.get(blah).success($scope.peeps = data.peeps;);
};
它将更新视图上的$scope.peeps$scope.var通常是一个按钮 通常我会以角度返回$http承诺。服务的调用方可以使用success做任何它想做的事情。 但要保持向后兼容性,您可以尝试以下方法:
var getDataFromServer = function () {
var peeps = [];
$http.get("../../TestData/peeps.json").success(function(data) {
peeps.push.apply(peeps,data);
});
return peeps;
}
因此,您将返回一个初始为空的数组。但是它将被json数组填充。通常我会以角度返回$http承诺。服务的调用方可以使用success做任何它想做的事情。
function myController($scope, $http){
$http.get(url).success(function(data){ $scope.people = data; });
}
但要保持向后兼容性,您可以尝试以下方法:
var getDataFromServer = function () {
var peeps = [];
$http.get("../../TestData/peeps.json").success(function(data) {
peeps.push.apply(peeps,data);
});
return peeps;
}
因此,您将返回一个初始为空的数组。但它将被json数组填充。控制台给我“错误:未知提供程序:$scopeProvider您必须将$scope注入您的服务。控制台给我”错误:未知提供程序:$scopeProvider您必须将$scope注入您的服务。
function myController($scope, $http){
$http.get(url).success(function(data){ $scope.people = data; });
}