我创建了一个服务,用于在两个控制器之间传递数据,但有些东西不能正常工作。
这是服务:
app.factory('SubmitService', function($rootScope) {
var data = {};
data.prepForBroadcast = function(recvData) {
data = recvData;
this.broadcastItem();
};
data.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return data;
});
它不是很复杂,它只需要在控制器之间传递一个对象。这些是在我的控制器中处理此服务的函数:
在发送控制器中(来自表单):
$scope.submit = function() {
submitService.prepForBroadcast($scope.formData);
}
在接收控制器(控制项目列表)中:
$scope.$on('SubmitService', function() {
this.pruebaNota.push(submitService.data);
});
我通过一个按钮调用提交功能,只需在onClick上调用:
<button class="btn btn-primary" style="height:35px;width:100px;float:right;" id="submit"
ng-disabled="isDisabled()" ng-click="submit()">
Enviar
</button>
编辑2:这是我的接收控制器及其测试阵列的一部分:
app.controller('noteController', ['$scope', 'SubmitService', function($scope, submitService) {
$scope.$on('handleBroadcast', function() {
this.pruebaNota.push(submitService.data);
});
this.pruebaNota = [{
"titulo":"Una nota de prueba",
"texto":"Un texto de prueba para ver qué tal funciona esto. Ejemplo ejemplo ejemplo!!!",
"fecha": new Date()
},
// more examples that aren't interesting at all
我想我在访问我的阵列时遇到了麻烦,但这是实际问题?我还是JS的新手。
答案 0 :(得分:1)
为了使其适用于数组修改,请在事件处理程序中引用适当的对象。
var self = this;
$scope.$on('handleBroadcast', function() {
self.pruebaNota.push(submitService.data);
});
注意:您的工厂相当混乱。它的工作原理是我见过的最奇怪的符号。
app.factory('SubmitService', function($rootScope) {
//ok: define a variable that will be returned and later injected into controllers
var data = {};
//ok: add functions to the object being returned
data.prepForBroadcast = function(recvData) {
//not evident: replace the variable accessible in closure with a new object
//if you try to modify existing data here instead of reassignment
//it will ruin the service injected to controllers
data = recvData;
this.broadcastItem();
};
...
return data;
});