使用$resource添加新项目

Add new item using $resource

本文关键字:新项目 添加 resource 使用      更新时间:2023-09-26

我是AngularJS新手。学习它。我使用AngularJS的web API的GET方法创建了产品列表。现在我想添加一个新产品。我正面临着几个问题。首先,我的ngDialog是自动关闭每当我点击它外面,我不知道如何使用$resource调用保存方法。这是我正在尝试的代码。

MyApp.controller('ProductController', function ($scope, $http, $resource, ngDialog) {
  Product = $resource('/api/Product')
  $scope.Product = Product.query();
  $scope.OpenProductForm = function () {
    ngDialog.open({ template: 'Product/AddNewTemplate.html' })
  };
  $scope.AddProduct = function () { 
    var NewProduct = $resource('/api/Product/:id', { id: '@id' });
    NewProduct.save();
  }
});

尝试将$resource服务路由添加到工厂中,并通过其方法在控制器中使用它:

MyApp.controller('ProductController', function ($scope, $http, yourResource, ngDialog) { 
  $scope.OpenProductForm = function () {
    ngDialog.open({ template: 'Product/AddNewTemplate.html' })
  };
  $scope.AddProduct = yourResource.save({id: id}, function (response) {
    $scope.id= response.id;
  };
}).factory('yourResource', ['$resource', function ($resource) {
  return $resource('/api/Product/:id', { id: '@id' } {
    'save': {
      method: 'PUT',
      headers: {"Content-Type": "application/json"}
    }
  });
}]);