我的服务中的CRUD操作有问题。当我点击Create Btn时,它正在创建一个对象,但它不会在表列表中推送该对象。
Ctrl(表格列表中的位置):
$scope.nameslist = CrudService.getAll();
Ctrl(用于模态对话框):
$scope.createItem = function (newObj) {
CrudService.create(newObj);
$scope.newObj = null;
$scope.ok();
}
CRUD服务(它是一个.factory):
...
return {
getAll: function () {
return resService.names.query();
},
create: function (newObj) {
resService.names.save(newObj);
//this.getAll.push(newObj); //this doesn't work
}
...
请求服务(也是.factory):
...
return {
names: $resource(baseUrl + '/api/names/:Id', {
Id: '@Id'
}, {
'update': {
method: 'PUT'
}
})
...
任何人都可以帮助我吗?如何在表格列表中推送新对象?
答案 0 :(得分:2)
创建对象后,您可以将对象推送到列表或调用getAll
$scope.createItem = function (newObj) {
CrudService.create(newObj);
$scope.newObj = null;
$scope.ok();
\\either
$scope.nameslist = CrudService.getAll();
\\or
$scope.nameslist.push(newObj); // this assumes this is an array
}
UPDATE /// $ broadcast将消息发送到子控制器,而$ emit发送它们。 使用$ rootscope。$ emit首先将其注入控制器
.controller('myCtrl' ['$scope', '$rootscope', function($scope, $rootscope ...
然后您可以使用$rootscope.$emit('added-Name')
,或者您甚至可以添加一个参数$rootscope.$emit('added-Name', {newObj: newobj})
然后在捕捉控制器
$rootscope.$on('added-Name'), function(event, args) {
$scope.namelist.push(args.newObj);
//or if you're not passing the argument
$scope.nameslist = CrudService.getAll();
});
使用共享服务:
angular.module('myApp').service('sharedService', function(){
var nameList = [];
return{
get: function(){
return nameList;
}
set: function(val){
nameList = val;
}
add: function(name){
nameList.push(name);
}
}
})
将sharedservice注入控制器 `.controller('ctrl',['$ scope','sharedService',function($ scope,sharedService ....
使用sharedService.set(CrudService.getAll());
填充服务中的nameList,并在$ scope.createItem中填写sharedService.add(newObj);
然后你可以在sharedService.get()
上看一下$scope.$watch(function() {
return sharedService.get();
}, function(newValue, OldValue) {
if (newValue !== OldValue) {
$scope.namesList = sharedService.get();
}
});