我是Angular的新手。我相信我在这里缺少一些基本的东西。
我有一个对象,我发布到服务器来创建它。服务器返回对象Id,我需要读取它并更新客户端中的对象。
服务器只返回对象ID,但是,在客户端,我有其他数据在执行回调时无法使用(我无法访问原始数据)。
The Following jsfiddle code has been added as a reference:
//Get Angular Project module
var app = angular.module("app", ['ngResource']);
//create Project factory
app.factory('Project', function ($resource) {
return $resource('http://cmsanalyticsdev.pearson.com\\:8081/api/projects/:projectid',
{projectid:'@id'},
{update: {method:'PUT', isArray:false}}
);
});
//Controller for testing
app.controller('ApplicationController', function ($scope, Project) {
//Project object
var project = new Project({"name":"New Project Test","thumbnail":"","statusid":"521d5b730f3c31e0c3b1e764","projecttypeid":"521f585c092a5b550202e536","teamid":"521f585a092a5b550202e521","authors":[{"firstname":"Dilip","lastname":"Kumar"}],"projectspecificmetadata":{"isbn13":"345345","guid":"asfas"},"modifiedby":"521f585a092a5b550202e525"}
);
//Create new project
project.$save(project, function (projectResponse) {
project.projectId = projectResponse._id;
alert(project.name);
});
});
答案 0 :(得分:6)
我想你想要这样的东西:
//Controller for testing
app.controller('ApplicationController', function ($scope, Project) {
//Project object
var projectData = {"name":"New Project Test","thumbnail":"","statusid":"521d5b730f3c31e0c3b1e764","projecttypeid":"521f585c092a5b550202e536","teamid":"521f585a092a5b550202e521","authors":[{"firstname":"Dilip","lastname":"Kumar"}],"projectspecificmetadata":{"isbn13":"345345","guid":"asfas"},"modifiedby":"521f585a092a5b550202e525"};
var project = new Project(projectData);
//Create new project
project.$save(project, function (projectResponse) {
projectData.projectId = projectResponse.id;
console.log("ProjectData: %j", projectData);
});
});
答案 1 :(得分:1)
以下是$ update的类似方法。
//keep original data to pass into callback
var originalProjectObject = angular.copy(project);
//Call server to update the project data
project.$update({ projectid: project._id }, function (projectResponse)
{
originalProjectObject._id = projectResponse._id;
//update scope
scope.project = originalProjectObject;
},originalProjectObject);