假设我有一个项目列表,其中包含通过加载 JSON 对象的非常简单的服务从服务器检索的数据。像这样:
MyApp.factory("ItemList", function($resource) {
return $resource("/api/items", {}, {
"get":{
method: 'GET'
},
"add":{
method: 'POST'
}
});
});
如果我通过 POST 向服务器添加一些东西到这个列表,它工作正常,但我不太清楚如何在不重新加载整个页面的情况下让新项目出现在我的 View 中。
我的 Controller 现在看起来像这样:
MyApp.controller('ListController', function($scope, ItemList) {
$scope.items = ItemList.query();
$scope.addItem = function() {
var form = {
"item" : "Some content",
}
ItemList.add(form);
};
});
现在事情变得棘手了。我考虑过重写服务以将新项目推送到存储在服务中的数组,但每个新项目在发布时都有一个由服务器添加的唯一 ID。长话短说,我需要刷新整个资源,或者从服务器获取新的唯一 ID(这是可能的,API 支持)并将组合数据附加到列表。
我不想为此使用任何 JQuery。完成列表更新的 Angular 方法是什么?
附加数据:可能有帮助的一件事是,当一个项目被发布到服务器时,它会用项目的内容和唯一 ID 进行响应。但是,我不确定使用 Angular 方法来获取它并将其添加到列表中。
截至 2015 年 11 月 23 日的解决方案 多亏了下面的答案,我整理了一个可行的 CRUD-ish(“ish”是因为由于应用程序的运行方式,CRUD 并不完美满足我的需求)解决方案,我将在下面解释。
首先,这是我的新资源:
// Added $http for ease of getting JSON results
factory("ItemList", function($resource, $http) {
var service = {};
// Simplified $resource object for querying. Posts handled by $http now.
service.items = $resource("/api/items:id");
// Make the items an array accessible from inside the service.
service.list = service.items.query();
service.add = function(item) {
$http.post('/api/items', item)
.success(function(data) {
service.list.push(data);
})
.error(function(data) {
console.log(data);
});
}
return service;
});
然后我所要做的就是改变我的 Controller ,像这样:
MyApp.controller('ListController', function($scope, ItemList) {
// Grab the array from the service instead of querying the resource
$scope.items = ItemList.list;
$scope.addItem = function() {
var form = {
"item" : "Some content",
}
ItemList.add(form);
};
});
这工作得很好,使我无需重新加载整个页面,而且速度非常快。我将在未来尝试对此进行改进 - 希望通过使其更像 CRUD,但与此同时,这是可行的。我希望其他人觉得它有用。
最佳答案
如果您确信服务器端的数据没有变化(引用 Lazarev Alexandr 的评论),我会将新数据附加到现有列表中。
$http.post('/someUrl', data).then(
function(data){ // on success
$scope.yourlist.push(data);
},
function(data){ // on error
console.log(data);
});
该服务将返回一个 promise ,然后当 POST 完成时,它应该返回新的返回项,您可以将其添加到当前列表中。
我可能是错的,但我觉得通过不重新加载现有数据,这种方法稍微更“有 Angular ”。
网络接口(interface):
public class InfoController : ApiController
{
[HttpPost]
public IHttpActionResult AddInfo([FromBody]InfoClass info)
{
object o = new object();
return Json(o);
}
}
public class SomeClass
{
public string firstname { get; set; }
public string lastname { get; set; }
}
关于javascript - 如何在将新项目发布到服务器后更新 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33878522/