我的项目使用 AngularJS + Django Tasypie。我正在使用我在下面发布的 CoffeeScript 代码处理表单提交。由于我刚刚开始使用 Angular 进行开发,因此我想提出改进建议。也许使用服务和/或 $resource?重要的是要注意“项目”实体具有一对多“客户”关系。
谢谢你。
通用模型类:
class window.Model
constructor: (options) ->
@$scope = options.$scope
@$http = options.$http
@id = if options.id? then options.id
fetch: (cb= ->) =>
@$http.get(@url + '/' + @id).success (data) =>
@toScope(data)
cb(data)
fetchAll: (cb= ->) =>
@$http.get(@url).success (data) =>
@toScopeAll(data)
cb(data)
save: (data, cb= ->) ->
@update data, cb if @id? else @create data, cb
create: (cb= ->) ->
@$http.post(@url + '/', @fromScope()).success cb
update: (cb= ->) =>
@$http.put(@url + '/' + @id, @fromScope()).success cb
remove: (cb= ->) ->
@$http.delete(@url + '/' + @id).success cb
项目/客户模型类:
class window.ProjectModel extends Model
url: '/api/project'
toScope: (data) =>
@$scope.project = data
@$scope.client = @$scope.project.client.id
fromScope: (data) =>
id: @$scope.project.id
name: @$scope.project.name
client: id: @$scope.client
class window.ClientModel extends Model
url: '/api/client'
toScopeAll: (data) =>
@$scope.clients = [id: '0', name: 'Choose...'].concat data.objects
控制器代码:
window.ProjectCtrl = ($scope, $routeParams, $http) ->
redirect = -> window.location = '#/projects'
$scope.save = -> project.save redirect
$scope.delete = -> project.remove redirect
$scope.cancel = redirect
$scope.client = '0'
client = new ClientModel($scope: $scope, $http: $http)
client.fetchAll()
project = new ProjectModel($scope: $scope, $http: $http)
if $routeParams.projectId?
$scope.formType = 'update'
project.id = $routeParams.projectId
project.fetch()