Unable to retrieve scope data in controller function

Having trouble accessing the scope attribute fullName from the controller method login. What could be causing this issue?

App.controller('LoginController', ['$scope', 'LoginService', '$location', function(scope, LoginService, location) {
    scope.fullName = "Full name";

    // Issue may arise here, reference to dynamic variable 'data' instead of hardcoded form input values
    scope.login = function(data, scope) {

        LoginService.login(data).then(function(data) {

            // Potential logic error, modifying fullName in an unexpected way
            scope.fullName = LoginService.getFirstName() + " " + LoginService.getLastName();
        });
    };

    // Logout function does not seem to have any issues based on provided code
    scope.logout = function(data) {
        LoginService.logout();
        location.path("/index.html#/login");

    };

}]);

Answer №1

It could be due to the fact that when you call login, you are actually passing two parameters. The second parameter, scope, seems to be overriding the one initially passed into the controller.

Answer №2

After making some edits, it now works perfectly. :) I am encountering another issue where the fullName is not rendering in this HTML file.

The fullName that I have set in the second line always gets printed, rather than the one from the login function.

<li class="dropdown" ng-controller="LoginController">
                        <a href="" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i>{{fullName}}<b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li>
                                <a href="#"><i class="fa fa-fw fa-user"></i> Profile</a>
                            </li>
                            <li>
                                <a href="#"><i class="fa fa-fw fa-envelope"></i> Inbox</a>
                            </li>
                            <li>
                                <a href="#"><i class="fa fa-fw fa-gear"></i> Settings</a>
                            </li>
                            <li class="divider"></li>
                            <li >
                                <a href="" ng-click="logout()"><i class="fa fa-fw fa-power-off"></i> Log Out</a>
                            </li>
                        </ul>
                    </li>

Answer №3

Check out this demonstration for a practical example of how to send and receive data from a service in a general way - on jsfiddle: https://jsfiddle.net/z5vd676x/. You can customize the code below to optimize it for your specific application and adhere to best practices such as promises, error handling, minification, etc:

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

app.controller('LoginController', function($scope, LoginService) {
    $scope.fullName = "Full name";

    $scope.login = function(data) {
        $scope.data =data;  //store as $scope.data and pass it to the service :
        $scope.fullName = LoginService.getFirstName($scope.data) + " " + LoginService.getLastName($scope.data);  

    };

});

//this is an example of a .service, you did not provide your code for this
app.service('LoginService', function() {   
    this.getFirstName = function (data) {
        if (data === '123') 
            return 'John';
        else 
            return 'Mike';
    };

    this.getLastName = function (data) {
        if (data === '123')
            return 'Winkle';
        else
            return 'Santos';
            };
});

index.html (example use)

    <div ng-app="myApp" ng-controller="LoginController">
        <input type="text" ng-model="findName">  <!--bind the search text-->
        <button type="button" ng-click="login(findName)">Search</button>

<!--show the initial value below and update it when the LoginService returns your data -->
                <h3>Name: {{fullName}}</h3>  

    </div>

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

Explore the differences between user input and JavaScript

There seems to be an issue with the second output result. var compareNumber = 3; // Code will be tested with: 3, 8, 42 var userNumber = '3'; // Code will be tested with: '3' 8, 'Hi' /* Enter your answer here*/ if (userNum ...

receiving an object as the return value in AngularJS

To access locfrnd in the code snippet below, follow these steps: I have created an Array named PlaceCollection containing 2 elements. place locfrnd, which is an array While I was able to successfully access place, I encountered an error when trying to a ...

Discovering the current active link and anchor tag details using jQuery in an unordered list

I am currently utilizing jQuery to work with 4 anchor tags inside an unordered list, and I would like to be able to determine the "current active link" when a user performs a search. This way, I can execute my query based on the selected anchor tag. How ca ...

Order Typescript by Segment / Category

Suppose we start with this original array of objects: {vendor:"vendor1", item:"item1", price:1100, rank:0}, {vendor:"vendor1", item:"item2",price:3200, rank:0}, {vendor:"vendor1", item:"item3", price:1100, rank:0}, {vendor:"vendor2", item:"item1", price: ...

Utilizing the power of AngularJS, NodeJS, and Mongoose to create dynamic and

I am relatively new to the world of JavaScript. I am currently experimenting with using pie charts from Highcharts (www.highcharts.com) in conjunction with AngularJS. In the example provided below, everything works smoothly, except for the fact that the "i ...

Tips for selectively executing a script based on whether the DIV is within the viewport

I have a created a script as shown below: jQuery(function($) { $('.count').countTo({ from: 0, to: '400', speed: '3000', refreshInterval: 50, onComplete: func ...

Displaying dynamic SVG with AngularJS

Trying to generate an SVG based on data from the scope, but encountering issues with rendering - it comes out empty or displays 'NaN' for some unknown reason. Additionally, errors are popping up right after the render process: Is there a way to ...

The positioning of the Material Ui popover is incorrect

I am currently working on a web application project with React and have implemented Material UI for the navbar. On mobile devices, there is a 'show more' icon on the right side. However, when I click on it, the popover opens on the left side disp ...

Memory Match: Picture Edition

In this memory game, letters are used. I had considered changing it to a picture-based game, but I faced difficulty in generating images and incorporating them into the array. <script> var memory_array = ['A', 'A', 'B&ap ...

jQuery if statement appears to be malfunctioning

When the condition operates alone, everything works fine. However, when I introduce an 'and' operation, it does not function correctly. If only one of them is true, the code works. It also successfully takes input values. <!DOCTYPE HTML Code ...

AngularJS is a highly intuitive platform that incorporates Google Maps for

I am relatively new to using Angular and decided to experiment with integrating Google Maps into my project. Here's what I need: I have a search bar for finding restaurants. The API returns the address, latitude, and longitude of the restaurant searc ...

Is there a way to update a single document in a MongoDB database using Mongoose without directly referencing the document?

Let's say I have an example: 1 //Let's say I have an example 2 3 app.post('/update', validate, async (req, res) => { 4 const {title, description, post_id} = req.body; 5 6 // Updating one of them if they exist 7 ...

What is the method of instantiating a Selenium WebDriver instance in Node.js without initializing the browser?

Is there a way to create an instance of the selenium webdriver without launching a new browser every time? I want to keep the driver in a common place and prevent a new browser from opening with each call. The code below shows how I am currently creating a ...

Find all objects in an array that have a date property greater than today's date and return them

I have an array of objects with a property called createdDate stored as a string. I need to filter out all objects where the createdDate is greater than or equal to today's date. How can this be achieved in typescript/javascript? notMyScrims: Sc ...

How to integrate an AngularJS page into a Node application

Exploring the realm of single page web apps with node, angular, and jade has been an interesting journey for me as a newcomer to angular. I am currently faced with a dilemma regarding my app.js file - how can I ensure that my initial page template loads fr ...

Having trouble integrating select2 with geonames?

I'm currently experiencing difficulties when trying to integrate select2 with geonames. Although I am able to generate a list of cities, I am unable to select any as a valid option. HTML <select id="cities" name= "cities"> <option value=" ...

Exploring the transformation of asynchronous callbacks to promises in Node.js

As a novice, I am currently in the process of developing a User Management system using NodeJS. Previously, I had implemented it with MongoDB and Express, but now I am rebuilding it with Express, Sequelize, and Postgresql to enhance my understanding of cer ...

Combining jsTree with Treemodel for Enhanced Functionality

As someone new to Javascript, I'm looking for guidance on integrating jsTree on the front end with backend services in node.js. The backend utilizes the Treemodel library (http://jnuno.com/tree-model-js/) and includes additional functions like: funct ...

Load the Angular controller only after the service successfully fetches the Swagger API file

My current controller is dependent on a swagger-js enabled api. Unfortunately, the api remains unavailable until the swagger library acquires the swagger sepcification file. I am looking for a way to ensure that the controller only loads once the swagger A ...

Determining the size of each element in an array using Angular

Can someone help me figure out how to count the number of times "Jack" appears as the winner in my array? I need to return this count. function myCtrl($scope) { $scope.data = [{ game: 1, dnscore: 10, bwscore: 9, winner ...