Creating operations in Angular using the Model View Controller (MVC)

What is the procedure for performing an Add operation in MVC using Angular?

var addProductModule = angular.module("addProductModule", []);

addProductModule.factory("addProductService", ['$http', function ($http) {
return
{

    function saveProduct(productToSave)
    {
        $http({

            url : 'AddProduct',
            method : "POST",
            data : productToSave
        })

        return productToSave;
    }
};
}])

Answer №1

Component :

var productComponent = angular.module("productComponent", []);

Service

productComponent.factory("addProductService", ['$http', function ($http) {
    var _saveProduct = function(productToSave)
    {
        var promise = $http({

            url : 'api/Product/AddProduct',
            method : "POST",
            data : productToSave
        })

        return promise;
    }

    return  {
      saveProduct : _saveProduct
    }
 }
}]);

Controller :

productComponent.controller("addProductController", 
 ["addProductService", function(addProductService) {

  $scope.addProduct = function(product) {
     addProductService.saveProduct(product)
             .then(function success(response) {
          //  do something on success
     }, function error(reason) {
         // do something on error
     });
  }
}]);

API Endpoint

public class ProductController : ApiController
{
     public ActionResult AddProduct(Product p)
      {
         // add the product
      }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

Having trouble inputting text into input field using ReactJS

I am currently facing a challenge while attempting to modify the value of an input field using ReactJS. The issue I am encountering is the inability to input values into the field. After reviewing several other queries, it appears that simply changing the ...

Each slider only displays a single database entry

I have an array that retrieves testimonials from a database table and displays them using a foreach loop. I am looking to implement a slider that can fade in and fade out the results. Here is my database query: $showTestimonials = array(); $getTestimoni ...

Accurate date and time depiction at a high resolution using JSON and JavaScript

Is there a standardized method for displaying high-resolution timestamps in JSON and/or JavaScript? It would be ideal to have support for at least 100 ns resolution, as it would simplify the server code (due to the 100 ns resolution of the .NET ...

Footer button overrides list components due to improper implementation of vertical ion-scroll

Having some trouble setting up ion-scroll on a specific screen in my mobile application built with Ionic. On the Book page of my app, I'm encountering two main issues: https://i.stack.imgur.com/MnheG.png 1) The placement of the Confirm button doesn& ...

Adjusting the height of a vertical slider in Vuetify2 is not customizable

I've been trying to adjust the height of a vertical slider in vuetify2, but setting it to "800px" or using style="height:800px" doesn't seem to work as intended. Even though the box within my grid expands, the height of the slider remains unchan ...

What is the best way to display multiple modals in a React app?

I am facing a challenge where I need to render multiple modals based on the number of items in the 'audios' property of an object. Currently, I am using the mui modal library for this functionality. Here are the variables being utilized: const ...

The problem with escaping characters in Javascript occurs when a backslash is duplicated within an object

My intention was to save the JSON object with an escape character by escaping "/". I achieved this by using string replace to convert my string into "\/". Afterwards, I assigned this to an object variable and attempted to console log it, only to find ...

Display issue with Google Chart

Could someone please help me identify why these charts are not showing up? This code was functioning properly in a previous project. I copied the same code to a new project, only adding the master page. However, now the charts are not appearing. All I can ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

Utilize Next.js with Axios for making an HTTP request to a Laravel Lumen endpoint, then showcase the retrieved data within the Next.js

I currently have a Next.js application that utilizes Axios to make calls to Lumen endpoints. The Axios HTTP client functions are organized in a separate folder named services/index.tsx, with sample code as follows: export const register = async (payload: a ...

Implementing delayed loading of Angular modules without relying on the route prefix

In my application, I am using lazy loading to load a module called lazy. The module is lazily loaded like this: { path:'lazy', loadChildren: './lazy/lazy.module#LazyModule' } Within the lazy module, there are several routes def ...

Discovering methods to store browser credentials securely in jQuery

I need to prevent the login button from being enabled when either the username or password fields are empty. Check out the code snippet below: $(document).ready(function(){ $('input').on('keyup blur mouseenter', function(e) { ...

Nodemailer is experiencing difficulties when used within the routes directory

Recently, I encountered an issue with my subscribe form. It functions perfectly when called from app.js where the express server is defined. However, when I move subscribe.js to the routes folder and connect both files, it fails to send emails. Upon pressi ...

Examining the contents of an array in JavaScript

I am currently conducting API testing. My objective is to verify the presence of a specific name within the API response. The data from the API response is structured in an array format. Despite my intention to check for the existence of the name "activ ...

What is the best method for managing an event loop during nested or recursive calculations?

When it comes to breaking a computation and releasing using setTimeout(), most examples seen involve having a shallow call stack. But what about scenarios where the computation is deeply nested or mutually-recursive, like in a tree search, with plenty of c ...

Encountering an EJS error stating SyntaxError: a closing parenthesis is missing after the argument list in the file path C:Userscomputer pointDesktopproject2viewshome.ejs

Struggling to retrieve data from app.js through ejs and encountering an error. Pursuing a degree in Computer Science <%- include('header'); -%> <h1><%= foo%></h1> <p class = "home-content">It is a fact that readers ...

Steering clear of using HTML tables to display company data

I am eager to enhance the way I present business data to my users. Currently, I am involved in developing a web application management system using MVC Razor .NET, Entity Framework, and Angular JS. One specific page requires displaying a significant amou ...

Ways to address time discrepancies when the countdown skips ahead with each button click (or initiate a countdown reset upon each click)

Every time I click my countdown button, the timer runs normally once. But if I keep clicking it multiple times, it starts skipping time. Here are my codes: <input type="submit" value="Countdown" id="countdown" onclick="countdown_init()" /> <div i ...

Creating a universally accessible handlebars helper in ExpressJS

I have a basic handlebars helper file located in helpers/handlebars.js: var hbs = require('express-handlebars'); hbs.registerHelper("inc", function(value, options) { return parseInt(value) + 1; }); Unfortunately, I am unable to utilize the ...