我正在嘗試在資源承諾內實現角模型,但問題在於此模型未定義。資源承諾內角模型爲null
基本上我有產品列表顯示在頁面上和所有產品我有一個刪除操作。我希望在成功刪除產品後,在頁面上實現產品列表。
我的資源定義:
angular.module('bookshop').factory('productsFactory', function($resource, serverUrlValue) {
return $resource(serverUrlValue + '/bookshop/products/:id', {
id: '@id',
query: '@query'
}, {
update: {method: 'PUT'},
search: {method: 'GET', params: '@query', url: serverUrlValue + '/bookshop/products/search', isArray: true}
});
});
我的控制器的定義:
angular.module('bookshop').controller('cmsProductsController', function($state, $stateParams, utilService, productsFactory, categoriesFactory) {
this.products = productsFactory.query();
//skipped methods
this.remove = function(productId) {
//here object looks good
console.log(this.products);
this.result = productsFactory.delete({id: productId}).$promise.then(function() {
//here object is undefined
console.log(this.products);
this.products = productsFactory.query();
})
}
});
我的HTML:
<tr ng-repeat="product in cmsProductsCtrl.products track by $index">
<td>{{product.name}}</td>
<td>{{product.price | currency}}</td>
<td>
<a ng-click="cmsProductsCtrl.remove(product.id)" href="">
<span class="glyphicon glyphicon-trash icon-sm"></span>
</a>
</td>
</tr>
可以用於管理控制器和視圖我使用的UI路由器。
我的路由定義:
angular.module('bookshop').config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider.state('cms.products', {
url: '/products',
controller: 'cmsProductsController',
controllerAs: 'cmsProductsCtrl',
templateUrl: 'core/cms/products/cms-products.tpl.html'
});
});
從調試屏幕:
UPDATE
得益於@Jesus卡拉斯科我解決我的問題,通過這些變化控制器
解決方案:
angular.module('bookshop').controller('cmsProductsController', function($state, $stateParams, utilService, productsFactory, categoriesFactory) {
this.products = productsFactory.query();
//skipped methods
this.remove = function(productId) {
var model = this;
//object looks good
console.log(model.products);
productsFactory.delete({id: productId}).$promise.then(function() {
//object also looks good
console.log(model.products);
model.products = productsFactory.query();
});
}
});
檢查此產品。因爲你在一個函數裏面。這個。在功能範圍內。所以而不是嘗試使用var vm = this;和vm.products –
你還沒有在'resource'上創建一個刪除方法... – Pureferret
默認情況下資源沒有創建刪除方法[link](https://docs.angularjs.org/api/ngResource /服務/ $資源) – grkopiec