The functionality of ng-click and ng-submit seems to be malfunctioning

I am currently facing an issue with my Angular application and PhoneGap. I have a login form along with a login controller set up, but for some reason, the ng-submit function is not working as expected. When the submit button calls the formConnexion() function, nothing happens. I even tried using an alert instead, but faced the same result...

Next, I attempted to use ng-click, but again, no luck. Additionally, when I tried to display a sample variable in the template ($scope.test), it didn't show up. Also, the console.log('salut!!') statement doesn't appear when I'm on the login page.

All these issues led me to think that my controller might not be correctly associated with the template, even though I have included the ng-controller with the correct name in my div element.

Initially, I suspected that there might be something wrong with the angular installation, but all other directives like ng-if and ng-src seem to be working fine.

If anyone has any insights or solutions to this problem, I would greatly appreciate the help :)

Below is the code snippet for the template:

login.html

<div class="row jumbotron" style="margin:10px" ng-controller="LoginCtrl">
    <div class="col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-2 col-sm-8 col-sm-offset-2 col-xs-8 col-xs-offset-2">
        <h1>{{ test }}</h1>
        <form class="form-horizontal" ng-submit="alert('alert')">
            <div class="form-group">
                <label for="login" class="control-label">Login</label>
                <input type="text" name="login" class="form-control" ng-model="formData.login">
            </div>
            <div class="form-group">
                <label for="password" class="control-label">Password</label>
                <input type="password" name="password" class="form-control" ng-model="formData.password">
            </div>
            <button type="submit" class="btn btn-md btn-success">Connexion</button>
        </form>
        <a href="" ng-click="alert('lalalala')">click</a>
        <img ng-src="images/accueil.png" class="accueil img-responsive">
    </div>
</div>

And here is the controller:

login.js

'use strict';

appStat.controller('LoginCtrl', function ($scope, $rootScope, $http, $location) {
    console.log("salut!!");
    $scope.formData   = {};
    $scope.test = "test";
    $scope.toto = function() { alert('alert'); };

   /**
    * Connect user
    */
    $scope.formConnexion = function () {...}

  });

Lastly, here is my app.js:

app.js

'use strict';

var appStat = angular.module('posStatsPhoneGap', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngRoute',
    'ngResource',
    'ui.bootstrap',
    'ngMessages',
    'ngAnimate',
    'ngAria',
    'ngTouch',
    'picardy.fontawesome'
])
    .config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {

        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|tel):/);
        $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|tel):/);

        $routeProvider
            .when('/', {
                templateUrl: 'views/login.html',
                controller: 'LoginCtrl'
              })
            .when('/main', {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
              })
            .when('/stat', {
                templateUrl: 'views/stat.html',
                controller: 'StatCtrl'
              })
              .otherwise({
                redirectTo: '/'
              });

  }
]);

Any assistance would be highly appreciated!

Answer №1

Here is a suggested approach based on my previous comment:

  1. Start by creating a Controller file and adding a controller inside it for your Angular application

  2. Create an angular module within the controller file

To create a controller.js file, follow these steps and refer to the code snippet below:

// Within your controller.js file 
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope, $http){

  $scope.Data = "Alert Alert";

  // Define a function within the scope of the module
  $scope.myFunc = function(){
      alert($scope.Data)
  };
});

Next, you can call the function on click in your HTML file with the following code snippet:

Note: Make sure to include the controller in your HTML code. I typically add it within the body tag.

<body ng-controller="myController">
   <button ng-click="myFunc()">Click me</button>
</body>

Check out a live example here:

http://plnkr.co/edit/sQ0z7TlyWv5fM5XyfujK?p=preview

Additionally, keep in mind that ng-click is commonly used for handling click events in Angular applications, while ng-submit is more suitable for form submissions in HTML.

Answer №2

Ensure to include ng-submit in your form like this:

<form ng-submit="submit()">

function Controller($scope) {
    $scope.data = [];
    $scope.text = 'hello';
    $scope.submit = function () {
        if ($scope.text) {
            $scope.data.push($scope.text);
            $scope.text = '';
        }
    };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
    <div ng-controller="Controller">
        <form ng-submit="submit()">Type something and press enter:
            <input type="text" ng-model="text" name="text" />
            <input type="submit" id="submit" value="Submit" /> <pre>data={{data}}</pre>

        </form>
        <button ng-click="submit()">Submit Now</button>
    </div>
</div>

Answer №3

The issue has been identified. The problem arose from duplicating the name 'LoginCtrl' for two controllers, resulting from a careless copy and paste mistake.

Answer №4

I have successfully developed code to handle the specified question for 4 different types of HTML elements. For the complete code, please visit the URL below -

http://plnkr.co/edit/Tm2Rtbt3xsv4pKzcPQCw?p=preview

<body ng-controller="ExampleController">
    <button ng-click="setButton()">set button</button>
    <div content="snippetContentFirst"></div>
    <div content="snippetContentSecond"></div>
    <div content="snippetContentThird"></div>
    <div>
        <ul content="snippetContentFour"></ul>
    </div>
</body>

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

By checking the active box and completing the fields, the button will be activated

I'm currently working on a form that requires all fields to be filled out and the acceptance checkbox to be checked before the Submit button becomes active. If any entry or the checkbox is subsequently removed, the button should become inactive again. ...

What steps can be taken to resolve the error message: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data?

I'm facing an issue while trying to retrieve data for my map using an AJAX call. The error message I receive is: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Interestingly, two previous datasets in my applicatio ...

Encountered a $resource configuration issue while making a request to the SharePoint REST service with Angular

In an old sample app without angularJS, a rest service is called in the following way: This app does not use angularJS. var listName = "Events"; // the url to use for the REST call. var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target ...

retrieve the parent frame's request URL

I am faced with the task of writing a JSP code that retrieves the getRequestURL() of the parent frame (the URL shown in the address bar) from a child frame. However, when I attempt to do this, I only obtain the URL of the child frame. Is there anyone who ...

Utilizing data interchange within AngularJS services

How can data be shared between services in AngularJS? A scenario where data aggregation is needed from various services For instance, having a service1 retrieving data from a REST Service and then service2 adding supplementary data from another REST API ...

Retrieving chosen items from NextUI-Table

I am completely new to JavaScript and NextUI. My usual work involves C# and DotNET. I have a requirement to create a table with selectable items, and when a button is clicked, all the selected items should be passed to a function on the server that accepts ...

When executing npm run dev, an UnhandledPromiseRejectionWarning is triggered

I'm encountering an UnhandledPromiseRejectionWarning error when running npm run dev on my Vagrant machine, and I'm struggling to identify the root cause. The console output suggests that a promise is not being properly completed with the catch() ...

What is the best way to remove the hover effect from a specific element within a div?

I am looking to achieve a specific hover effect where the white part does not darken when hovering over a certain element within its child elements. Here is the HTML code I have: <div className= {css.searchBarDiv}> <div className={css.searchBar ...

Fuel Calculation - Unable to pinpoint the error

My JavaScript Code for Calculating CO2 Emissions I'm working on a program that calculates how much CO2 a person produces per kilometer. This is part of my school project and I'm still learning, so please bear with me... I also just signed up on ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

Jquery not functioning properly for show and hide feature

I'm new to using Jquery and JqueryUI. I have a div named front, which I want to initially display on window load and then hide it by sliding after a delay of 5500 milliseconds. However, I'm encountering errors in the jquery.min.js file. The HTML ...

The placement of Bootstrap Datepicker is experiencing issues

I have integrated the Bootstrap Datepicker from Eternicode into my ASP.Net MVC website. While the functionality is working well, I am facing difficulty in positioning the datepicker modal using the orientation option mentioned in the documentation and code ...

What steps are needed to successfully integrate bootstrap.js, jquery, and popper.js into a project by using NPM to add Bootstrap?

I've successfully set up a project and incorporated Bootstrap via npm. However, I'm facing challenges in loading the necessary javascript files for Bootstrap components. It's important to note that I am utilizing a Vagrant Box (virtual machi ...

Using JavaScript's document.write method to display HTML code, along with a variable retrieved from a Flash application

Can I ask two questions at once? Firstly, how can I achieve the following? document.write(' <div id="jwplayer"> <center> <div id='mediaplayer'></div> <script type="text/javascript"> jwplayer('mediapl ...

What is the best way to automatically hide the Materialize CSS mobile navbar?

Recently, I completed a website called Link. Using only Materialize CSS, Vanilla JS, and plain CSS, I developed a single-page application that effectively hides and reveals different sections based on event listeners. Everything functions smoothly except ...

What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up: 'use strict'; var lunchrServices = angul ...

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

If someone rapidly clicks on an AngularJS app, the page fails to load

Just a heads up - I am pretty new to Angular. Most of the code is from a tutorial on Lynda that I'm experimenting with. I've noticed an issue when I try to implement a type of "pagination" feature to display various elements from a data.json file ...

What is the best method for inserting a 'Placeholder' in an Angular datePicker?

Looking for assistance with placing placeholder text inside an Angular datePicker, specifically wanting to display 'From' and 'To' labels within the datePicker. datePicker I am a novice when it comes to Angular development - can someon ...

Utilize Angular to connect NavBar partial HTML with a controller variable

Encountering an issue where my search term in the navigation bar is not binding to a controller variable due to it being out of scope. Attempting to utilize ng-model in the partial HTML navbar to connect the input value with the controller variable. Parti ...