我创建了一个用于在两个 Controller 之间传递数据的服务,但有些东西无法正常工作。
这是服务:
app.factory('SubmitService', function($rootScope) {
var data = {};
data.prepForBroadcast = function(recvData) {
data = recvData;
this.broadcastItem();
};
data.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return data;
});
这并不是很复杂,只需在 Controller 之间传递一个对象即可。这些是我的 Controller 中处理此服务的函数:
在发送 Controller 中(来自表单):
$scope.submit = function() {
submitService.prepForBroadcast($scope.formData);
}
在接收 Controller (控制项目列表)中:
$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:这是我的接收 Controller 及其测试数组的一部分:
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 还是个新手。
最佳答案
为了使其适用于数组修改,请在事件处理程序中引用正确的对象。
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;
});
关于javascript - 在服务不工作的 Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31912636/