Having trouble retrieving the value of an object in Angular

I have an AngularJS factory named 'userFactory' that I'm using:

app.factory('userFactory', function($window) {
    var auth = {
        isLogged: false,      
        user: "a",
        check: function() {
            if ($window.sessionStorage.token) {
                this.isLogged = true;
            } else {
                this.isLogged = false;
                delete this.user;
            }
        }
    }
    return auth;
});

To test it out, I added some static content inside a controller. On clicking a button, the following code runs:

// replace "a" with the following
app.controller('LoginCtrl', ['$scope', '$window', '$location', 'userFactory',
    function ($scope, $window, $location, userFactory) {     
        $scope.login = function(){
            var userCredentials = {
                "username": $scope.username,
                "password": $scope.password
            };
            if (userCredentials.username == "amir" && userCredentials.password == "blum") {
                userFactory.isLogged = true;
                userFactory.user = {
                    "name": "amir",
                    "surname": "blumenfeld"
                };
                $location.path("/customer");
            } else {
                alert("NO");
            }
        }
    }
]);

Then, trying to display the surname "blumenfeld" on the page:

function menuCtrl($scope, $location, userFactory, $window) {
    $scope.user = userFactory.user.surname;
}

The expected output should be "blumenfeld" here:

<ul ng-controller="menuCtrl">                
    <li><a href="#home">{{ user }}</a></li>                                                                                                    
</ul>

But unfortunately, all I see is just an empty space.

I need assistance in identifying where I went wrong and how I can correct it.

Thank you!

Answer №1

It appears that there is an issue with how you are setting the value of $scope.user to userFactory.user.surname upon creation. Essentially, your user is assigned as a and surname as undefined.

Subsequently, in your click event, you are assigning userFactory.user to an object. However, since $scope.user remains undefined, it does not recognize that its value depends on userFactory.user, resulting in a constant value of undefined.

To resolve this issue, you need to assign the object within your factory to an object itself. Additionally, in your click event, update the values without altering the object.

var app = angular.module('MyApp', []);
app.factory('userFactory', function($window) {
    var auth = {
      isLogged: false,      
      user: {
         name: "a",
         surname: "a",
         job: "a",
      }
    }
    return auth;
  });

app.controller('menuCtrl2', ['$scope', 'userFactory', function($scope, userFactory){
  $scope.load = function () {
    userFactory.user.name = "amir"
    userFactory.user.surname = "blumenfeld"
    userFactory.user.job = "crazy" 
  }
}]);

app.controller('menuCtrl', ['$scope', 'userFactory', function($scope, userFactory){
  $scope.user = userFactory.user;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="MyApp">
  <div ng-controller="menuCtrl2">
     <button ng-click="load()">Load</button>
  </div>
  <div class="row" ng-controller="menuCtrl">
    {{user.surname}}
  </div>
</div>

Here's an alternative approach using a method:

var app = angular.module('MyApp', []);
app.factory('userFactory', function($window) {
    var auth = {
      isLogged: false,      
      user: {
         name: "a",
         surname: "a",
         job: "a",
      }
    }
    return auth;
  });

app.controller('menuCtrl2', ['$scope', 'userFactory', function($scope, userFactory){
  $scope.load = function () {
    userFactory.user = {"name":"amir", "surname":"blumenfeld", "job":"crazy"};
  }
}]);

app.controller('menuCtrl', ['$scope', 'userFactory', function($scope, userFactory){
  $scope.user = function () {
    return userFactory.user.surname
  }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="MyApp">
  <div ng-controller="menuCtrl2">
     <button ng-click="load()">Load</button>
  </div>
  <div class="row" ng-controller="menuCtrl">
    {{user()}}
  </div>
</div>

Answer №2

After pasting your code, I noticed that it is functioning correctly. Take a look here

var myApp = angular.module('myApp', []);
myApp.factory('userFactory', function($window) {
    var auth = {
      isLogged: false,      
      user: "a"
    }
    return auth;
  });
function MyCtrl($scope, userFactory) {
    userFactory.user = {"name":"amir","surname":"blumenfeld","job":"crazy"};
     $scope.user = userFactory.user.surname; 
}

Answer №3

Experiment with constructing a user object without using quotation marks around property names:

userFactory.user = {name:"amir",surname:"blumenfeld",job:"crazy"};

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

What is the best way to access the local Express server that is located in the same directory as the frontend project

This is the structure of my project - backend > node_modules > .env package-lock.json package.json server.js frontend > index.html style.css script.js server.js import dotenv from 'dotenv'; dotenv.config(); import express from &apo ...

Providing the full response object when resolving a promise from $http

Recently, I encountered an issue with a method in one of my service used for making API calls. The method looks like this: this.postData = function(requestURL, requestObj) { var deferred = $q.defer(); console.log("Reached APIService @POST", reques ...

The use of callbacks in Model.findById() is now deprecated due to a MongooseError

Hello there! I've run into an issue and could use some assistance, thank you in advance! Running MONGOOSE VERSION: "mongoose": "^7.0.3" Error Message: MongooseError: Model.findById() no longer accepts a callback at Function.findB ...

An issue arises with ReactJS MaterialUI Stepper when there is an overflow

My struggle with the Material UI Stepper component persists as I attempt to make it suit my requirements, specifically to display multiple steps and handle overflow. However, it stubbornly continues to misbehave by showing unusual separators when there is ...

Postman is showing a 404 error message when trying to access an Express JS route that uses a POST request

Currently, I am working on creating APIs in Node.js with express and body-parser. While GET requests work fine using Postman, there seems to be an issue with POST requests as it consistently throws a 404 error saying Cannot GET / Express Version: @4.17.1 ...

The useEffect hook is causing a loop of API calls after successfully fetching data

I've been working on fetching data from my API and then performing some mappings to present it in the desired format. The challenge I'm facing is that the API calls are asynchronous, so I need to wait for the response before updating my dataset. ...

Issue with aligning items vertically using CSS and Javascript

I must admit, I am not well-versed in CSS. My goal is to create a performance bar using CSS and Javascript. So far, I have managed to generate a background bar with another bar inside that fills up to a specific percentage. However, my issue lies in the fa ...

Error: controller undefined

As I delve into a Coursera course on AngularJS, I've encountered a perplexing issue with a controller. The console is indicating that it is not defined. Upon running it through the https://validator.w3.org/, a recurring error message mentioning that ...

The lifecycle of transitions in Nuxt 3

I have implemented Nuxt 3 layout transitions using JavaScript hooks to smoothly transition between layouts. The transition consists of two parts, one triggered by the onLeave hook and the other triggered by the onEnter hook on the next layout. This setup e ...

Switch the status of an individual item within a datalist using jQuery in an ASP.NET application

Currently, I have a database with Titles that are displayed using a datalist, where the content is initially hidden. The objective is to reveal the hidden content when each item is clicked, achieved through jQuery implementation. Below is the code snippet ...

How can we ensure that the slider thumb label is always shown in Angular 16 Material components?

Is there a way to display the thumb label constantly on a material slider? The solution mentioned above does not seem to work with Angular 16 material UI slider. Could you kindly offer an alternative solution for this issue? ...

The attribute 'inventory' cannot be found in the declaration of 'WarehouseModule'

I am facing an issue with my AngularFire setup. I have recently installed the latest version of AngularFire using npm i @angular/fire and have successfully configured Firestore. However, when attempting to load data into my Firestore database, I encounte ...

Incorporating jQuery functions in the Angular app's main component file, app

I've been working on an Angular application and recently added the jQuery package with the following code: $ npm install jquery --save Now, I am attempting to transfer data from my HTML web page's .js file to the app.component.ts in Angular. I ...

The browser Internet Explorer fails to recognize the @media screen rule

Currently, I'm focusing on creating a responsive design for a web page. The issue I am encountering involves loading data via ajax to render forms. Strangely, only Internet Explorer seems to think that the width is less than 768px after rendering (thu ...

The Javascript Keydown event seems to fire twice

When the user presses ctrl + z, I want to trigger an undo action by handling a keydown event on the document. This is how I have set up the event listener in my document: componentWillMount() { window.addEventListener('keydown', throttle(this ...

What is the best way to consistently display a scroll bar at the bottom?

How can I ensure that the scroll bar is always at the bottom when loading pages? I need an immediate solution. The JavaScript code seems to be malfunctioning. Please assist me in resolving this issue. #student_name{ height:315px; } <div id ...

Using experimental.externalDir in NextJS prevents the use of absolute imports in external libraries

In my monorepo setup with nextjs, lerna, and npm workspaces, the folder structure is as follows: packages next-js-app pages index.tsx tsconfig.json ui-library src components dropdown. ...

Transmitting occasional feedback from ASP.NET Web API function to jQuery AJAX

I am currently working on a project that requires sending intermittent status responses from a Web API method back to a jQuery AJAX call in order to display progress in the UI. https://i.sstatic.net/Y6R4w.png The process involves the jQuery AJAX calling ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

I encountered a CORS policy error while using React. What steps can I take to effectively manage and resolve this

INDEX.JS import express from "express"; import { APP_PORT } from "./config"; import db from "./database"; import cors from "cors"; import bodyParser from "body-parser"; import Routes from "./routes&quo ...