What could be causing the ng-submit to fail to trigger the $scope.submit function?

I am currently working on my App.js file which contains the following code snippet:

var app = angular.module('githubApp', []);

In addition to that, I have a githubAppController with the following code block:

app.controller('githubController', function ($scope, $http) {
    $scope.submit = function () {
        var promise = $http.get('https://api.github.com/users/odetocode');
        promise.then(onUserGet);

        var onUserGet = function (response) {
            $scope.user = response.data;
        };
    };
});

Furthermore, within my page.html file, the following code is present:

<!DOCTYPE html>
<html >
<head>
    <title></title>
    <meta charset="utf-8" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/custom.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.9.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="Scripts/jquery.validate.min.js"></script>
    <script src="Scripts/App.js"></script>
    <script src="Scripts/githubController.js"></script>
</head>
<body ng-app="githubApp">
    <div ng-controller="githubController">
        <form class="form-horizontal" ng-submit="submit()">
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">

                    <input type="submit" id="submit" class="btn btn-primary" value="Submit" />
                    <input type="reset" id="submit" class="btn btn-primary" value="Reset" />
                </div>
            </div>
        </form>

        <div class="col-sm-5">
            <label>{{user.name}}</label>
        </div>
        <div class="col-sm-7">
            <a ng-href="{{user.blog}}">{{user.company}}</a>
        </div>

        <div>
            <img ng-src="{{user.avatar_url}}" />
        </div>
    </div>

However, I am facing an issue where the ng-submit directive does not trigger the $scope.submit function. Can you please assist me in identifying what might be causing this problem?

var app = angular.module('githubApp', []);
app.controller('githubController', function($scope, $http) {
  $scope.submit = function() {
    var promise = $http.get('https://api.github.com/users/odetocode');
    promise.then(onUserGet);

    var onUserGet = function(response) {
      $scope.user = response.data;
    };

  };
});
<!DOCTYPE html>
<html>

<head>
  <title></title>
  <meta charset="utf-8" />
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>

<body ng-app="githubApp">
  <div ng-controller="githubController">
    <form class="form-horizontal" ng-submit="submit()">
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">

          <input type="submit" id="submit" class="btn btn-primary" value="Submit" />
          <input type="reset" id="submit" class="btn btn-primary" value="Reset" />
        </div>
      </div>
    </form>
    <div class="col-sm-5">
      <label>{{user.name}}</label>
    </div>
    <div class="col-sm-7">
      <a ng-href="{{user.blog}}">{{user.company}}</a>
    </div>

    <div>
      <img ng-src="{{user.avatar_url}}" />
    </div>
  </div>

Any help or suggestions would be greatly appreciated. Thank you.

Answer №1

let promise = $http.get('https://api.github.com/users/odetocode');
promise.then(onUserGet);

let onUserGet = function (response) {
  $scope.user = response.data;
};

onUserGet is not defined when called here. It must be defined before being used for it to work correctly.

Therefore, submit is actually triggered despite your belief. However, because of the issue in the code, you do not see the intended outcomes.

Answer №2

Here is the code snippet you can use.

$scope.saveData = function() {

        var result = $http.get('https://api.github.com/users/username');
        result.then(function(res) {
          $scope.data = res.data;
        });

Answer №3

To implement this functionality in your controller, you can use the code snippet below:

var app = angular.module('githubApp', []);
app.controller('githubController', function ($scope, $http) {
    $scope.submit = function () {
        console.log("Executing function");
        $http.get('https://api.github.com/users/odetocode').success(function(data){
          $scope.user = data;
        })
    };
});

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

Can the function be executed without the need for ng-app?

After researching my AngularJS application, I discovered that having 2 ng-app tags in the html file means only the first one will be executed. In my code snippet below <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"> ...

Passing $scope variable to child controller in AngularJS $modal

JavaScript Code, var mod= $modal.open({ animation: true, templateUrl: $scope.url, controller: function($scope, $modalInstance,custObj) { alert(custObj); /*************Line 1**************************/ $scope.save = function() ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

The creation of an indexedDB database and the addition of content encountered an error while trying to perform a 'transaction' on the IDBDatabase

I am relatively new to using IndexedDB and have successfully created a database. However, I am encountering an error when trying to add content to it. The specific error message reads: Uncaught NotFoundError: Failed to execute 'transaction' on ...

Using SVG in a Vue standalone script without the need for a build step is easy with the

When I attempt to utilize Vue as a standalone script in an HTML file, my inline svg icons are rendered as solid filled squares instead of their intended shapes. This issue persists when using both Vue 2 and Vue 3 as standalone scripts. Although there are ...

When working with React, I often encounter situations where I receive very similar Unix timestamps from the `<TextField type="date">` component

I am facing an issue with setting the start date and due date using two Textfield components. Check out the code snippet below: const startDateChange = (e) => { setStartDate(Math.floor(new Date().getTime(e.target.value) / 1000)); console.log(startD ...

Issues with JavaScript causing YouTube embed player to malfunction

For the past few days, I've encountered an issue where my JavaScript code to embed YouTube videos isn't working properly. The video loads but it's not playable as the play button is unresponsive. The console shows this error: Uncaught TypeE ...

Find the smallest number within an array without relying on the Math function

Could someone assist me in creating a function that finds the lowest number in an array? I've been struggling with this and previous answers on similar questions didn't really help as they presented solutions with unfamiliar code. The current cod ...

Angular route is completely unresponsive

I initiated the %a{"ng-click"=>"get_destinations(city)"} Nevertheless, it was supposed to direct me to the "destinations" controller, but that wasn't the case There are no errors in the web console – what could be ...

Encountering a problem while trying to install ionic-native using npm

I encountered an error while working with npm and Angular: $ npm install ionic-native --save <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a5a8a6b5a3abaea9a287f6e9f7e9f7">[email protected]</a> /home/louisro/Doc ...

Django not receiving data from AJAX GET request

I am attempting to transmit data stored in localStorage through an AJAX GET request to Django, but the Django server does not seem to receive it. I have verified that there is data in localStorage("preselection") as indicated by the output of console.log. ...

Enhancing caching through JSPM optimization

I have successfully configured my workflow to utilize JSPM, resulting in the creation of a production bundle consisting of two large injected and hashed files called main-{hash}.min.css and main-{hash}.min.js. My inquiry pertains to the efficiency of sepa ...

npm run is having trouble locating the graceful-fs module

I am currently enrolled in a course on DjangoRest and React. While I have experience with npm and Python, I have encountered an error that I am unable to resolve. Everything was going smoothly until I ran "npm run dev." package.json file { "name": "fron ...

Caution: Refs cannot be assigned to function components

I'm currently using the latest version of Next.js to create my blog website, but I keep encountering an error when trying to implement a form. The error message reads as follows: Warning: Function components cannot be given refs. Attempts to access t ...

Error message encountered: ReferenceError - The subcommand specified in Discord.js Slash Command function is undefined

I have been experimenting with subcommands in a slash command for a discord bot. I plan to have several similar subcommands, so I wanted to create a function that can be called within .addSubCommand, but it seems like it's not functioning correctly. ...

Transformation of Object into Number through Function Execution in Javascript

I am currently facing an issue with my animate() function while using Three.js to generate an animation. Below is a simplified version of the code: let obj; let camera = new THREE.PerspectiveCamera(fov, asp, near, far); let scene = new THREE.Scene(); const ...

I encountered a sudden halt in functionality with my NextJs useState feature

'use client' import React, { useState } from 'react'; import Image from 'next/image'; export default function Home() { const [count,setCount] = useState<number>(0) const add = ()=> { setCount(prevCount => ...

I encountered some problems with conflicting Angular dependencies, so I decided to delete the node_modules folder

An error has occurred: The module 'H:\All_Files\Scripts\Angular\example\node_modules\source-map\source-map.js' could not be found. Please ensure that the package.json file contains a correct "main" entry. ...

Websocket issues with onopen function not consistently triggering in AngularJS application

I am currently working on an application that is reading data from an external device. My chosen JavaScript framework is AngularJS and I am using angular-ui for routing purposes. To ensure that the web socket can be accessed across multiple screens, I am ...

JavaScript Class experiencing issues with returning NAN when using the Multiplication method

Currently, I have a JavaScript Class with a multiplication method that aims to multiply all elements of an array excluding those that are undefined. To achieve this, I utilized a for loop to check the data type of each element (ensuring it is a number) and ...