AngularJS - The ngClick function is not functioning properly / The getAll() function is not defined

Being new to Angular has been quite challenging for me. I've attempted various approaches and codes from different sources.

I have a simple view that retrieves/ adds data from a database via WEBapi.

3 questions:

1/ Why is IE not passing the data to the view here? 2/ What am I doing wrong in Chrome that prevents the SUBMIT action from working? 3/ What is the best approach to make it work on both browsers?

I can't seem to figure out what's going wrong. The Chrome console doesn't show any errors, but ngclick does not submit the form.

https://i.sstatic.net/yQZNV.png

On the other hand, IE fails to display the data in the list and shows an error in the console.

https://i.sstatic.net/60nEx.png

Regarding the WEBapi, it seems to be functioning correctly (tested using both browsers and Fiddler).

index.html

@{    Layout = null; }
<!DOCTYPE html>
<html lang="pl">
... [omitted for brevity] ...



module.js (consolidating code from other .js files)

<pre><code>var app;
(function () {
    app = angular.module("APIModule", []);

    app.service("APIService", function ($http) {

        this.getParcels = function () {
            var urlBase = 'http://localhost:1797/api';
            return $http.get(urlBase + '/webapi');
        }

        this.saveParcel = function (par) {
            var urlBase = 'http://localhost:1797/api';
            return $http.post(urlBase + '/webapi', par);
        }
    });
    app.controller("APIController", function ($scope, APIService) {


        getAll();

        $scope.getAll = function () {
            var servCall = APIService.getParcels();

            servCall.then(function (d) {
                $scope.parcel = d.data;
            });
        };

        $scope.addParcel = function () {

            var parcel = {
                Name: $scope.Name,
                PostalCode: $scope.PostalCode,
                City: $scope.City,
                Phone: $scope.Phone,
                Email: $scope.Email,
                Street: $scope.Street,
                RegistrationDate: new Date()
            };

            var saveParcel = APIService.saveParcel(parcel);

            saveParcel.then(function (d, $scope) {
                // Return here
                $scope.getAll();
            });
        };


    });

})();

Answer №1

getAll function is currently undefined. When calling it from your controller, make sure to prefix it with $scope. If you try to call a function named getAll in the global scope without proper declaration, it will not exist. To fix this issue, follow these steps:

getAll();

$scope.getAll = getAll;
function getAll() {
  ...
}

By following this pattern, you can invoke the function with or without the $scope prefix.

Furthermore, the following code snippet needs correction:

var saveParcel = APIService.saveParcel(parcel);

saveParcel.then(function (d, $scope) {
  //returning here 
  $scope.getAll();
});

Avoid including $scope as a callback parameter since it may overwrite the existing $scope variable of your controller. Additionally, the d variable is unnecessary and should be removed. A revised version of the code would look like this:

var saveParcel = APIService.saveParcel(parcel);

saveParcel.then(function () {
  //returning here
  $scope.getAll();
});

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

Encountering the 'data is null' error when making a Twitter API request, yet the data is successfully displayed in the browser

I am attempting to show the number of followers for a Twitter account, but when I connect to the API using this code: $.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) { console.log ...

How can I transfer objects containing state information, such as connections, in ExpressJS?

This question delves into the architectural aspects of a project using ExpressJS, Angular, and Socket.io. The challenge at hand is how to persist the socket.io instantiation so that other parts of the project can utilize it effectively. Let's dive in ...

The NodeJs port is restricted to communication within the local network

After setting up a basic NodeJs server, the code looked like this: var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('hello world'); // try res.json() if getList() return ...

Changing various $scope object properties using ng-model

Can you help me figure out why the $scope.data variable is not updating when I input valid values in the form fields? How can I solve this issue? Check out the code example on Codepen: http://codepen.io/uloco/pen/jboorN HTML <div ng-app="app" ng-contr ...

Get started with the free plan for sails.js on Paas

Looking to test out my sails.js application deployment options. Can't seem to find sails.js on the supported list for Heroku and OpenShift's node.js offerings. Are there any free Platform as a Service (PaaS) plans available for sails.js? ...

Is there a way to remove a file that is currently being used by a read stream?

I am facing an issue where I cannot delete a folder after making a POST request because it is still in use by a read stream. Despite trying to use .destroy(); and .unpipe();, the folder remains in use. The only way I can delete files is by closing my Node. ...

Resolving an unhandled rejection issue with a promise in AngularJS Material's mdDialog

I'm encountering an unexpected unhandled rejection error with AngularJS Material's mdDialog when attempting to hide or cancel it. Here is the code snippet for the mdDialog: $scope.addAttendee = function(ev) { $mdDialog.show({ controller ...

Retrieve a JSON file with Hebrew data from a server and then interpret it using Node.js

I have a JSON file with dynamic content stored on a remote server acting as an API. The file also includes Hebrew text in its values. How can I retrieve the response and convert it into a JSON object? Here is the code snippet I have put together using Re ...

Bundle Thirdparty Dependencies with Webpack

I am looking to package a webpack bundle that includes all common third-party vendors such as Angular 1.4, jQuery, and other libraries. Currently, the following modules have been developed: Module A Vendor Module Vendor Module: Create a simple module ...

Guide to dynamically generating Angular watchers within a loop

I'm looking to dynamically create angular watches on one or more model attributes. I attempted the following approach: var fields = ['foo', 'bar']; for (var i=0, n=fields.length; i<n; i++) { $scope.$watch('vm.model.&ap ...

Utilize a method in Vue.js to filter an array within a computed property

I have a question regarding my computed property setup. I want to filter the list of courses displayed when a user clicks a button that triggers the courseFilters() method, showing only non-archived courses. Below is my current computed property implement ...

What is the best method to invoke a Spring MVC REST controller using Angular.js?

How can I connect an angularjs web form with a spring mvc REST controller to only refresh a small section of a page instead of the whole page upon form submission? In this scenario, only a specific element on the page should be updated after submitting th ...

When making an HTTP GET request followed by another GET request in Express, it results in an error with undefined parameters on the

When I open a form that has a link to a list and try to access the list, I encounter an "id" undefined error for the form we came from, which was already functional. The issue arises when I have a GET page where I present a form to modify a record at /loc ...

Receive the button click event outside of the canvas

Is there a way to have separate click events for the button and the ListItem? My focus is on the button click event only, without triggering the ListItem event. Live DEMO import React from "react"; import ReactDOM from "react-dom"; import ListItem from ...

Enclose the square brackets around the JSON.stringify(array) function to format the

I have been working on inserting an array of data into multiple columns in an sqlite database. Here is the code I have so far: function InsertData(dbData){ var valueArray = [], dataArray = []; var values = Object.keys(dbData); for(var key in values) ...

Using Facebook credentials to access a Grunt server

Currently, I am looking to test the functionality of Facebook login on my web application. At the moment, the Site URL listed in my Facebook app settings is: http://localhost:8080/#/SignIn I am utilizing grunt (specifically, running grunt server) to run ...

Browserify - Unveiling a Functionality on the Frontend

I seem to be struggling with Browserify. I would like to browserify my custom node module, which has a couple of functions exposed. How can I achieve this? In all the examples I've come across for browserify, it's always a console.log or an aler ...

I wasn't able to use the arrow keys to focus on the select box in my table, but I had no problem focusing on all

I'm a novice in jQuery and I encountered a situation where I have select boxes and text fields within my table. I successfully implemented arrow key functionality (down for next, up for prev) for shifting focus to the field by assigning classes to eac ...

I'm facing an issue where Typescript isn't recognizing Jest types

The Challenge Setting up a TypeScript project with Jest has been proving difficult for me. It seems that TypeScript is not recognizing the Jest types from @types/jest, resulting in an error message like this: Cannot find name 'test'. Do you nee ...

Updating the permanent placeholder text when selecting autocomplete results using JavaScript

I am seeking assistance with a javascript puzzle in my code. I am currently learning javascript and jquery, and although I may be a bit rusty, I am eager to get back into coding. One of the tasks I have accomplished is creating an autocomplete searchbox. T ...