The login controller fails to retrieve any values upon submission

My current controller setup looks like this:

var myApp = angular.module('myApp', ['ui.router']);
myApp.controller('loginController',['$http', function($http)
{
    this.loginForm = function(){
        console.log(this.email); //displays undefined
        console.log(this.password); //displays undefined
        var encodedString = 'email=' +
                encodeURIComponent(this.email) +
                '&password=' +
                encodeURIComponent(this.password);
        $http({
            method:'POST',
            url: 'rs/loginResource',
            data: encodedString,
            headers: {'Content-Type' : 'application/x-www-form-urlencoded'}
        });
    };
}]);

The values of this.email and this.password are returning as undefined in the current implementation.

This is how my form is structured:

<!-------------- loginController declared here (ERROR when declared)------------------->
<div class="row" ng-controller="loginController as loginCtrl"> 
<div class="col-md-12">
    Login via
    <div class="social-buttons">
        <a href="#" class="btn btn-fb"><i class="fa fa-facebook"></i> Facebook</a>
        <a href="#" class="btn btn-google" ><i class="fa fa-google"></i> Google</a>
    </div>
    or

    <!------------------------------------ Here is the form ---------------------------------------------------------->

    <form class="form" role="form" method="post" ng-submit="loginCtrl.loginForm()" accept-charset="UTF-8" id="login-nav">
        <div class="form-group">
            <label class="sr-only" for="exampleInputEmail2" ng-model="loginCtrl.inputData.email">Email address</label>
            <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>
        </div>
        <div class="form-group">
            <label class="sr-only" for="exampleInputPassword2" ng-model="loginCtrl.inputData.password">Password</label>
            <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password" required>
            <div class="help-block text-right"><a href="">Forget the password ?</a></div>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-primary btn-block">Sign in</button>
        </div>
        <div class="checkbox">
            <label>
                <input type="checkbox"> keep me logged-in
            </label>
        </div>
    </form>

    <!------------------------------------ End of form ---------------------------------------------------------->
</div>
<div class="bottom text-center">
    New here ? <a href="#"><b>Join Us</b></a>
</div>
</div>

I attempted to retrieve the values using

console.log(this.email); console.log(this.password);
, but both returned undefined. Are there alternative methods to access values in AngularJS?

Answer №1

If you're aiming to work without the constraints of scope, consider exploring "TypeScript". It seamlessly integrates with Angular for a "scope-free" experience using "ControllerAs".

To address your issue--> Initially, you are referencing "inputData.email" & "inputData.password" but then attempting to access them as .email and .password.

Next, ensure to pass 'this' into the function like so:

function loginController() {
                var _this = this;
                this.loginForm = function () {
                    console.log(_this.inputData.email);
                    console.log(_this.inputData.password);
                    var encodedString = 'email=' +
                        encodeURIComponent(_this.inputData.email) +
                        '&password=' +
                        encodeURIComponent(_this.inputData.email);
                    $http({
                        method: 'POST',
                        url: 'rs/loginResource',
                        data: encodedString,
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                    });
                };

For a head start on combining Angular with TypeScript, check out this helpful resource (highly recommended!)
http://www.codeproject.com/Articles/888764/Getting-started-with-TypeScript-in-AngularJS-appli

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 setting up a select dropdown in AngularJS using ng-options when the value is an object

How can I set the initial selection of a select field using ng-options? Consider the items we have: $scope.items = [{ id: 1, label: 'aLabel', subItem: { name: 'aSubItem' } }, { id: 2, label: 'bLabel', subItem: { ...

Unable to transfer files, encountering issues with PHP and AngularJS integration

I am currently working on uploading files using both AngularJS and PHP. For the AngularJS part, I am utilizing angular-file-upload from https://github.com/danialfarid/angular-file-upload. I suspect that the issue lies in my PHP code, as it fails to move ...

Combining Elasticsearch with AngularJS or Node.js

I am currently developing a MEAN stack application that utilizes elasticsearch for searching records. In my AngularJS controller, I have implemented the following code to interact with the elasticsearch server: instantResult: function(term) { var client = ...

What are the best practices for managing user forms and uploading files?

How should data in text fields and file upload fields be handled according to best practices? This question is a more generalized version of one I previously asked, which can be found here. Let's consider the scenario of a user registering an accoun ...

collaborative data interchange in angularjs controllers

When it comes to managing shared state between controllers, I often struggle to find the best approach among the many options recommended on forums like Stack Overflow. To help clarify my thoughts, I've created a simple diagram outlining my basic idea ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

Error: Attempting to access property 'original_title' on an undefined object

Visitors to my website have the option to search for a specific movie title. A dropdown list will then display all matching titles, allowing users to click on a title to add that movie to their watchlist. Upon clicking a title, the function addMovie is tr ...

Evaluating Jasmine unit tests using promises with odata

I am new to working with Angular and unit testing in Angular. Our project involves using odata for performing CRUD actions on the database, so we have created a service for this purpose. Here is a snippet of our service code: function DatabaseService($htt ...

Utilize AngularJS to enable the forward and back buttons to fetch JSON data, but ensure that the data is only retrieved if the item meets

I have successfully implemented forward and back buttons for paging through data items in an array from a JSON file: Controller: dishControllers.controller('DrinkcardsController', ['$scope','$http','$routeParams', ...

Integrating external JavaScript libraries into Ionic using the correct process

For the last few months, I have been utilizing jQuery Mobile for a hybrid app. Now, I am interested in exploring Ionic and Angular.js, so I am attempting to reconstruct it. My current JQM application relies on xml2json.js, but I do not have any experience ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

Error in D3: stream_layers function is not defined

Utilizing nvd3.js to construct a basic stacked bar chart as detailed here I inserted the code provided in the link into an Angular directive like this: app.directive('stackBar', function() { return { restrict: 'A', ...

AngularJS Directory Listing

I need to iterate through a list of folders using ng-repeat, here is my code snippet: HTML: <div class="container" ng-controller="miControlador"> <li class="left-menu-list-submenu"> <a class="left-menu-link" href ...

Issue encountered while installing npm via command line

Currently in the process of installing node on my Mac and encountering an error. I downloaded Node from the official website and executed the package, but I am still facing issues. Can anyone advise me on why this error is occurring when I attempt to run ...

ES6 Class Directive for Angular 1.4

I am currently exploring the possibility of incorporating a directive from version 1.4 and adapting it to resemble a 1.5 component. By utilizing bindToController and controllerAs, I aim to integrate the controller within my directive rather than using a se ...

Unable to verify $http using passport Basic Authentication

How do I implement $http call with basic auth using Passport? I have successfully set up basic authentication with Passport on my server and can test it using POSTMAN. However, when trying to implement it in my Angular application, I am facing issues pass ...

"Error: Page not found - node.js and angular.js are unable

I've successfully set up the root route, but I'm encountering an issue with another route at 127.0.0.1:3000/dashboard. When I directly enter this URL into the address bar, I receive the following error: Cannot GET /dashboard However, if I creat ...

What is the method to access the controller value within a metadata tag?

One of the challenges I am facing is how to access a variable from a controller and use it in a metadata tag using AngularJS. Below is my approach: First, let's define the variable in the controller: app.controller('homeCtlr', function($sc ...

UI-Router - Displaying and concealing elements dynamically in response to state changes

I am currently dealing with a situation where I have implemented dynamic showing and hiding of a button based on state changes. However, there seems to be a noticeable delay when the button is supposed to hide. The button itself is created as a directive ...

Error: Undefined Property in Angular 2 ViewChild Declaration

Exploring a simple example where the childMethod is called within the child component from the parent component using the @ViewChild() decorator. However, encountering an issue where the ViewChild variable remains undefined. Sample Child Component Code: ...