【发布时间】:2013-11-28 22:11:17
【问题描述】:
我有一个像这样的小型 AngularJs 应用程序:
// html
<div ng-repeat="project in projects">
<h3>{{ project.id }}</h3>
<h3>{{ project.title }}</h3>
<div ng-repeat="task in project.tasks">
<h4>{{ task.id }}. {{ task.title }}</h4>
<button class="btn btn-default" ng-click="showEditTask=true">Edit Task</button>
<div class="box row animate-show-hide" ng-show="showEditTask">
<h2>Create a New Task</h2>
<form name="newTaskForm" class="form-horizontal">
Title: <br />
<input ng-model="new_task.title" type="text" id="title" name="title" class="form-control" placeholder="Title" required /><br />
Project: <br />
<select ng-model="new_task.project" ng-options="project.title for project in projects" class="form-control"></select><br>
</form>
<button class="btn btn-success" ng-click="createTask(new_task)" ng-disabled="!newTaskForm.title.$valid">create</button>
</div>
</div>
</div>
// app.js
concernsApp.factory('ConcernService', function ($http, $q) {
...
update: function (obj_url, obj) {
var defer = $q.defer();
console.log(obj)
$http({method: 'POST',
url: api_url + obj_url + obj.id + '/',
data: obj}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
defer.reject(status);
});
return defer.promise;
},
});
concernsApp.controller('ProjectsCtrl', function ($scope, $http, ConcernService) {
$scope.updateTask = function(obj) {
ConcernService.update('tasks/', obj).then(function(){
...
}
});
问题在于更新任务并保持父项目不变。如果我更改父项目,一切正常。如果我使用相同的父项目,那么我会得到:
TypeError: Converting circular structure to JSON
我不完全确定这里发生了什么。
编辑
所以,我可以这样解决问题:
$scope.updateTask = function(obj) {
parentProject = {'id': obj.project.id};
obj.project = parentProject;
ConcernService.update('tasks/', obj).then(function(){
...
});
};
这很有效,因为我实际上只需要task.project.id 来更新对象。我认为问题是由于任务引用了父项目,而父项目又引用了子任务等。我对此并不完全确定。
但是,这个解决方案对我来说似乎有点 hacky,我希望看到更好的解决方案。
【问题讨论】:
标签: json angularjs angularjs-scope