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

Error: Unable to access the applicant's ID as it is undefined

I'm currently facing an issue with passing parameters from server.js to humanresources.js in a login request. Although the params are successfully printed out in server.js, they appear as "undefined" once passed on to the function in human resources.j ...

Getting the parent object based on a filtered nested property can be achieved by utilizing a

I am currently facing an issue with filtering an array of nested objects. The problem arises when trying to filter the parent object based on a specific property within its child object. let line = "xyz"; let data = [ { "header": { ...

Storing files in DynamoDB using Reactjs is a convenient and efficient way

Is there a way to store resume files in an existing DynamoDB table that currently stores name and email information? I have attempted to do so using React's AWS package with the following code: <input name="my_file" onChange={e => upd ...

"Encountered an error when attempting to load a resource in Node

I'm currently taking a tutorial to learn Node and Angular. Coming from a LAMP stack environment, this new world feels overwhelming and confusing. Although I have installed Angular JS and included it in my HTML file, I keep encountering the following ...

Load upcoming and previous slides in advance

Currently, I have implemented a basic slideshow on my website. It functions properly, but I am interested in preloading the previous and next slides to enhance its speed. Is there anyone who can assist me with this request? ...

Using jQuery to compel a user to choose a value from the autocomplete suggestions within a textarea

Currently, I have implemented a snippet that allows the user to choose cities from a list and insert them into a textarea separated by commas. However, I am looking to enhance this feature. I want the user to be able to search for a city by typing a part ...

Unusual behavior encountered while attempting to reset input text using AngularJS

I'm encountering an issue with what I assumed would be a straightforward scenario. Here is the form in question: <form class="form-inline" role="form"> <div class="form-group"> <input type="text" ng-model="customerInput" size="80 ...

With a tree arrangement flanking the Transfer module on either side

I have successfully implemented the antd's Transfer component using the examples provided in the documentation. I was able to create a tree transfer box that looks like this: However, I am wondering if there is a way to have a tree structure on both ...

Is it possible to extract content from a remote website by utilizing javascript and iframe?

Are there any resources available for working with iframes in Ruby on Rails? **UPDATE:** I have a link that directs to an external website. I am looking to extract the content from that site and save it within my application. Is this achievable without re ...

The dropdown menu in the navigation bar is overlapping with the datatable, creating a transparency effect

Working on a website layout that features a navbar at the top and a datatable below. However, when hovering over the navbar to reveal subitems, I notice a transparency issue where the navbar overlaps with the datatable. Below is a simplified version of my ...

Highlight dates in Vue.js that are overdue using a date filter

Currently, I have a Vue filter set up to display dates in a visually appealing way. However, I am looking to enhance the filter by adding a feature that would highlight dates in red if they are overdue (meaning the date is earlier than the current date). I ...

Tips for displaying a tooltip when hovering over a label in a Material UI slider

I'm currently working on a slider quiz and my goal is to have the tooltip appear when hovering over the label on the slider. Currently, I can only see the tooltip when I hover directly on the thumb at the location of my mouse. Refer to the image belo ...

A comprehensive guide on troubleshooting the toggleComplete functionality for React Todo applications

When you click on an item in the to-do list, it should show a strikethrough to indicate completion. However, when I try clicking on an item, nothing happens. Here is my toggleComplete function and where I am attempting to implement it: class ToDoForm exten ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

Encountering a value accessor error when attempting to test a simple form in Angular 4 and Ionic 3

My ionic form is quite simple: <ion-header> <ion-navbar> <ion-title>Foo</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="fooForm"> <ion-item> ...

Is it better to utilize a sizable JavaScript file or opt for a compact one?

I recently created a JavaScript file with over 6000 lines of code for various sections of my website. I'm debating whether to keep it as one large file or break it up into smaller parts and call them in their respective sections. What do you think? ...

Error: JSON at position 1 is throwing off the syntax in EXPRESS due to an unexpected token "

I'm currently utilizing a REST web service within Express and I am looking to retrieve an object that includes the specified hours. var express = require('express'); var router = express.Router(); /* GET home page. ...

When running through Selenium web driver, JS produces inaccurate results

Currently, I am utilizing JavaScript to determine the number of classes of a specific type. However, when I run the JS code in Webdriver, it provides me with an incorrect value. Surprisingly, when I execute the same JavaScript on the Firebug console, it gi ...

Incorrect interpretation of JavaScript object

To display some structured data on my JADE page, I created a JSON-like object containing variables, text, and JavaScript objects. Here is an example of what the JSON object looks like: var dataSet1 = { meta: { "name": "Some text", "minimum": mini_ ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...