我有物品服务,物品清单控制器和物品详情控制器:
.state('dashboard.items', {
url: '/items',
templateUrl: '/js/components/dashboard/items/items.html',
controller:'itemsListCtrl'
})
.state('dashboard.items.details', {
url: '/:id',
templateUrl: '/js/components/dashboard/items/itemDetails.html',
controller: 'itemDetailsCtrl',
resolve:{
items: function (ItemService) {
if(!ItemService.items)
ItemService.getAll().then(function (res) {
ItemService.items = res.data;
});
}
}
})
app.factory('ItemService', function ($http) {
var itemsFactory = {};
itemsFactory.getAll = function () {
return $http.get('/items');
}
itemsFactory.update = function () {
itemsFactory.items[0].name = "sadasd";
}
return itemsFactory;
})
app.controller('itemsListCtrl', function($scope, $state, ItemService){
if(!ItemService.items) {
ItemService.getAll().then(function (res) {
ItemService.items = res.data;
$scope.items = ItemService.items;
});
}else{
$scope.items = ItemService.items;
}
})
app.controller('itemDetailsCtrl', function ($scope, items, ItemService) {
$scope.item = ItemService.items[0];
$scope.item.name = "abc" ;
$scope.update = function(){
ItemService.update();
}
})
我有一个ng-click按钮,可以调用edit()函数。 我为示例做了简单的操作,在进行更新时,编辑项目名称时,列表中显示的项目不会更改。 我不知道我在这里想念的是什么。该列表位于服务中,两个控制器都将其用于其目的。
我做错了什么?这种情况的最佳做法是什么?
更新1 发现一些奇怪的东西。当我在控制器初始化中编辑项目时,它会全局更改原始值。当它通过edit()方法发生时,它不会。什么是幸福的?
感谢。
答案 0 :(得分:0)
$ http.get返回一个承诺,它会返回你的数据,所以。然后你可以做你的东西,它会在完成后执行(异步)
$http.get('/items').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response.data;//this is your data
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});