我在我的AngularJS应用程序中使用Restangular与后端API进行通信。在下面的示例中,样式还不是一流的,但由于我的问题与 html 无关,这并不重要。我的问题是change_status()
函数(和其他函数)仅适用于父函数(todo
),而不适用于子函数(child
)。因此,调用change_status(todo)
将完美工作,但调用change_status(child)
会给我一个todo.put is not a function
错误。我不明白这一点:传入父级应该产生与传入子级完全相同的结果,因为两者都是相似的对象(参见示例 JSON)。
我无法真正提供一个工作示例,因为此错误取决于与 API 的通信。但是,我已经包含了以下所有相关代码:
.HTML:
...
<tbody ng-repeat="todo in todos | filter:search" ng-hide="todo.hidden">
<tr>
<td style="width:100px" ng-click="change_status(todo)">
<span ng-if="todo.done" class="label label-success">Done</span>
<span ng-if="!todo.done" class="label label-warning">In Progress</span>
</td>
...
</tr>
<tr ng-repeat="child in todo.children | filter:search" ng-hide="child.hidden">
<td style="width:100px" ng-click="change_status(child)">
<span ng-if="child.done" class="label label-success">Done</span>
<span ng-if="!child.done" class="label label-warning">In Progress</span>
</td>
...
</tr>
</tbody>
...
控制器:
...
$scope.change_status = function(todo) {
todo.done = !todo.done;
todo.put();
$rootScope.todos = api.all('todo').getList().$object;
};
...
示例JSON(在ng-repeat中使用):
[
{
"description": null,
"title": "Learn to make a great todo-app using AngularJS",
"children": [
{
"description": null,
"title": "Learn AngularJS",
"children" : [],
"done": false,
"user": 1,
"hidden": false,
"id": 2
}
],
"done": false,
"user": 1,
"hidden": false,
"id": 1
}
]
Children 是一个普通的数组,没有 restangularization,所以你没有 restangular 方法,你必须重新排列它(检查 restangularizeCollection 方法)才能将其用于 restangular 方法(put)。父数组已经重新排列,因为它是你通过 restangular 调用检索的数组。
我使用了customPUT方法,它不需要我重新排列我的所有对象(这真的很难做到):
Restangular.allUrl('edittodo/' + todo.id).customPUT(todo)