我的“客户发票”应用程序的一部分包括[现在]的两个组件:发票清单和新发票模式表单。
视图如下所示:
%h2 Client Invoices
%div(ng-controller="ClientInvoicesCtrl as clientInvoicesCtrl")
%div(ng-controller="NewInvoiceModalCtrl as newInvoiceModal")
%a.button(href="#' ng-click="newInvoiceModal.open()") + New Invoice
%table
%thead
%tr
%th Client
%th Invoice #
...
%tbody
%tr(ng-repeat="invoice in clientInvoices")
%td {{ invoice.client.name}} ({{invoice.client.id}})
%td {{ invoice.id }}
...
我的逻辑就是这样:
app.controller 'ClientInvoicesCtrl', ['$http', '$scope', ($http, $scope) ->
$scope.clientInvoices = []
$http
.get '/clients/invoices.json'
.success (data) ->
$scope.clientInvoices = data.client_invoices
]
app.controller 'NewInvoiceModalCtrl', ['$modal', ($modal) ->
@open = ->
modalInstance = $modal.open {
templateUrl: '/clients/invoices/new'
controller: 'NewInvoiceModalInstanceCtrl'
windowClass: 'small'
}
]
app.controller 'NewInvoiceModalInstanceCtrl', ['$scope', '$modalInstance', ($scope, $modalInstance) ->
$scope.clientInvoice = {
id: ''
client_id: ''
start_on: new Date()
amount: ''
}
$scope.save = ->
# need to push $scope.clientInvoice into ClientInvoicesCtrl.clientInvoices
$modalInstance.close()
]
所以有一个控制器包裹整个部分,然后是一个模态控制器。
我想要做的是从NewInvoiceModalInstanceCtrl
进入ClientInvoicesCtrl
,将模式中新创建的发票传递到发票清单。我试图改变服务,以便在2个控制器之间进行通信,具体如下:
app.factory 'InvoicesSrvc', ->
return { clientInvoices: [] }
app.controller 'ClientInvoicesCtrl', ['$http', '$scope', 'InvoicesSrvc', ($http, $scope, InvoicesSrvc) ->
$scope.clientInvoices = InvoicesSrvc.clientInvoices
$http
.get '/clients/invoices.json'
.success (data) ->
InvociesSrvc.clientInvoices.concat data.client_invoices
]
...
app.controller 'NewInvoiceModalInstanceCtrl', ['$scope', '$modalInstance', 'InvoicesSrvc', ($scope, $modalInstance, InvoicesSrvc) ->
...
$scope.save = ->
# need to push $scope.clientInvoice into ClientInvoicesCtrl.clientInvoices
InvoicesSrvc.clientInvoices.push $scope.clientInvoice
# ... post request to submit to server ...
$modalInstance.close()
]
这似乎不起作用。将Array#concat
与绑定结合使用时似乎存在问题。
我为我的代码的2个版本(请参阅修订版)创建了GitHub Gist。
答案 0 :(得分:1)
而不是使用从外部引用的空数组,如下所示:
app.factory 'InvoicesSrvc', ->
return { clientInvoices: [] }
...
//later in the code
InvociesSrvc.clientInvoices.concat data.client_invoices
您可以编写一个存储相同数组的工厂,但会公开一些操作数据的方法。像这样的简单结构可以做到这一点:
app.factory('InvoiceSrvc', function () {
// your private data (and eventually functions) goes here
var clientInvoices = []
// your public API gets returned here
return {
addClientInvoice: function (invoice) {
clientInvoices.push(invoice)
}
}
})
然后,您可以添加操作数组所需的每种方法。