View $resource未更新视图
我有一个非常简单的资源,如下所示:View $resource未更新视图,view,resources,angularjs,updates,View,Resources,Angularjs,Updates,我有一个非常简单的资源,如下所示: angular.module('ExampleServices', ['ngResource']). factory('NoteService', function($q, $rootScope, $resource){ var baseurl = "/api/v1/note/"; var Note = $resource(baseurl, {}, { // get notes met
angular.module('ExampleServices', ['ngResource']).
factory('NoteService', function($q, $rootScope, $resource){
var baseurl = "/api/v1/note/";
var Note = $resource(baseurl, {}, {
// get notes method
get_for_model: {
method: 'GET',
params:{user: '', object_id: ''},
isArray: false
},
// leave note method
leave_note: {
method: 'POST',
}
});
return Note
}
);
$scope.note = function(){
$scope.note = NoteService.leave_note({
desc: desc,
title: title,
object_id: oid,
});
}
leave_note: function(){
var note = New Note();
note.desc = desc;
note.title = title;
note.object_id = oid;
note.$save();
$rootScope.$apply();
}
在控制器中,我调用leave\u note
方法如下:
angular.module('ExampleServices', ['ngResource']).
factory('NoteService', function($q, $rootScope, $resource){
var baseurl = "/api/v1/note/";
var Note = $resource(baseurl, {}, {
// get notes method
get_for_model: {
method: 'GET',
params:{user: '', object_id: ''},
isArray: false
},
// leave note method
leave_note: {
method: 'POST',
}
});
return Note
}
);
$scope.note = function(){
$scope.note = NoteService.leave_note({
desc: desc,
title: title,
object_id: oid,
});
}
leave_note: function(){
var note = New Note();
note.desc = desc;
note.title = title;
note.object_id = oid;
note.$save();
$rootScope.$apply();
}
这基本上是对我的应用程序RESTAPI调用POST方法,并创建对象。刷新页面后,我可以看到notes
中列出的注释。但就我所知,$resource
应自行更新视图
引自
重要的是要认识到调用$resource对象方法会立即返回一个空引用(对象或数组取决于isArray)。从服务器返回数据后,现有引用将填充实际数据
在我将其定义为函数(如下所示)之前,我无法在leave\u note
方法中使用$rootScope.$apply
但是在上述情况下,发送到RESTAPI的调用有一个未定义的
请求方法
我能想到的另一个问题是,我没有定义$scope.note
,但是定义了$scope.notes
,这是RESTAPI发送的注释列表。因此,可能正在更新$scope.note
,但由于我没有渲染note
对象,而是在模板中使用ng repeat
渲染notes
,因此我无法看到模板中的更改
我还尝试在保存一个新便笺后重新获取notes对象,但它基本上会删除所有便笺,然后重新呈现所有看起来很难看的便笺(几乎像页面刷新)
我试图实现的是,只要保存了
注释
对象,我就希望将新注释合并到现有注释中。请引导我。谢谢您不需要使用$rootScope.$apply
,您的小姐理解了$resource
API文档
正如$resource
文档中提到的:“一旦数据从服务器返回,现有的引用将填充实际数据。”。这意味着当您执行$scope.notes=NoteService.get_for_model()
您要求使用从NoteService.get\u model
get请求接收的(未来)数据填充$scope.notes
。$resource
API将负责完成这项工作—更新$scope.notes
模型—仅此而已。请注意,没有提到当您在同一服务上发布帖子时,您的数据将自动更新
如果要在添加新注释(POST)后更新$scope.notes
模型,并且不想请求整个注释列表,请尝试在POST成功回调中将新注释直接添加到$scope.notes
模型:
var note = NoteService.leave_note({
desc: desc,
title: title,
object_id: oid,
}, function() {
$scope.notes.push(note.$get());
}
);
请注意,这可以大大改进(即避免使用
$get
),但由于我不知道实现的确切细节,所以我只提供了一个通用解决方案。?请解释你的反对票。谢谢你抽出时间回应。实际上,我最终使用了$scope.notes.push(note)
,它确实更新了数据。干杯