The variable $scope.variable_name has not been defined

Working on websites using AngularJS has been a great way for me to enhance my skills with this framework. However, I have encountered an error that I need help troubleshooting.

The code in main-controller.js is as follows:

(function(){
angular.module('TimeWaste')
.controller('MainController', ['$scope', '$http', '$interval', function($scope, $http, $interval) {

    if(localStorage['User-Data'] !== undefined)
    {
        $scope.user = JSON.parse(localStorage['User-Data']);
        console.log($scope.user)
    }

    $scope.sendWaste = function(event) {
        if(event.which === 13)
        {
            var request = {
                user: $scope.user.username || $scope.user.email,
                userId: $scope.user_id,
                userImage: $scope.user.image,
                content: $scope.newWaste
            }

            $http.post('api/waste/post, request').success(function(response){
                console.log('fires')
            }).error(function(error){
                console.error(error);
            })
        }
    };
}]);
}());

The error I am receiving in the console is:

Error: $scope.user is undefined
$scope.sendWaste@http://localhost:3000/app/main/main-controller.js:15:6
anonymous/fn@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js line 216 > 
Function:2:319
Jc[b]       .compile/</</e@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js:257:177
    rf/this.$get</r.prototype.$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js:133:442
rf/this.$get</r.prototype.$apply@https://ajax.googleapis.com/ajax/libs/angu larjs/1.4.9/angular.min.js:134:170
Jc[b]          .compile/</<@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.    min.js:257:227 
m.event.dispatch@https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js:4:8497
m.event.add/r.handle@https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js:4:5235

https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js
Line 107

After analyzing the issue, it seems that $user.scope would be undefined if localStorage['User-Data'] is not defined.

However, I have already defined the localStorage['User-Data'] variable as:

"{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f989988f9897d78f988a9897b99e94989095d79a9694">[email protected]</a>","_id":"56c19d3a2c0b68545bd97793","username":"PLSV927","image":"/uploads/56c19d3a2c0b68545bd97793Fri Feb 19 2016 19:42:37 GMT-0800 (PST)morningbikeride.jpg"}"

I would appreciate any assistance in identifying what may have gone wrong. Could it be due to JSON.parse() not functioning properly or could there be a simple mistake that I overlooked? Please provide guidance.

Edit: Apologies for my oversight. The error was caused by incorrectly referencing $scope.user._id as $scope.user_id in the code snippet.

Answer №1

Change the following code

$http.post('api/waste/post, request')

to be like this

$http.post('api/waste/post', request)

Also, make sure to initialize $scope.user as an object at the start of the controller

$scope.user={};

Answer №2

To ensure proper initialization of the module, use angular.module('TimeWaste',[]) instead of angular.module('TimeWaste').

https://plnkr.co/edit/LKkAUN0U2DqPIhxY5ms9?p=preview

(function() {
  angular.module('TimeWaste', [])
    .controller('MainController', ['$scope', '$http', '$interval',
      function($scope, $http, $interval) {
        $scope.user;
        if (localStorage['User-Data'] !== undefined) {
          $scope.user = JSON.parse(localStorage['User-Data']);
          console.log($scope.user)
        }

        $scope.sendWaste = function(event) {
          if (event.which === 13) {
            var request = {
              user: $scope.user.username || $scope.user.email,
              userId: $scope.user_id,
              userImage: $scope.user.image,
              content: $scope.newWaste
            }

            $http.post('api/waste/post', request).success(function(response) {
              console.log('fires')
            }).error(function(error) {
              console.error(error);
            })
          }
        };
      }
    ]);
}());

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

Issues with Karma's base path functionality

I am encountering issues with launching tests using Karma for the first time. My folder structure is as follows: node_modules -angular-mocks src -compiled -lib -tests -karma.conf.js Within my karma.conf.js file, these are my file list and basepat ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

Creating a dropdown menu using Vue.js

My latest project involves coding an html page that features a drop-down list using HTML, CSS, and VueJS. The goal is to have something displayed in the console when a specific option from the drop-down list is selected. Here's the snippet of my html ...

Having issues with Google Maps API v3 not loading properly

I'm encountering an issue with initializing a map upon window load. While the problem is similar to this question, I am not utilizing jQuery to create the map, rendering the solution provided there inapplicable to my situation. Here's my code sni ...

Laravel has not been properly initialized

Recently, I've been exploring Laravel 5.3 and vue.js and I'm trying to make a GET request to fetch some user data from my database. I'm utilizing components in this project. Here is a snippet from my app.js file: require('./bootstrap ...

The color overlay for the class label map segmentation in AMI JS is not appearing as expected

I came across this example in vanilla JavaScript. In my project using Angular 7.3.8 with AMI version 0.32.0 (ThreeJS 0.99.0), I imported everything as an angular provider service. When trying the test examples from the provided link, I noticed that the o ...

Simulate a failed axios get request resulting in an undefined response

I'm having an issue with my Jest test mock for an axios get request, as it's returning undefined as the response. I'm not sure where I might be going wrong? Here is the component with the axios call: import {AgGridReact} from "ag-grid- ...

Implementing debounce functionality in Angular using CodeMirror

I've tried various approaches and even referred to This Possible Dup Currently utilizing the ng2-codemirror 1.1.3 library with codemirror 5.33.0 interface Simply attempting to add a DebounceTime operator to the change event of the CodeMirror Editor ...

Checking URL validity with regular expressions in Vue JS

Currently, I am attempting to validate URL strings utilizing a regular expression. The following regex is what I am using for this purpose: var regex = /^(http|https):\/\/+[\www\d]+\.[\w]+(\/[\w\d]+)?/ With thi ...

Can you explain the meaning of the ?. operator in JavaScript?

While using react-hook-form, I encountered the ?. operator. Can you explain its meaning? Here's an example of how it works: <span>{errors?.name?.message}</span> The errors variable is obtained from useForm() by destructuring, as shown bel ...

Ways to perform a force click on a span element when clicking on a glyphicon

There is a table cell containing two span elements: <span contentEditable=true class="editspan"></span> <span class="pencilspan glyphicon glyphicon-pencil pull-right"></span>" When clicking on span1, an input box appears for editi ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

Various designs for various arrangements in vuejs applications

In my project, I have two distinct layouts that function as separate parent routes with multiple nested components. I want to apply different global styles to each layout, but when I import styles for one layout, it affects the other as well: <style ty ...

Prevent Cordova from shrinking the view when focusing on an input

Currently working on developing an app using Cordova/Phonegap (v6.5.0). Platforms where I've installed the app: - IOS (issue identified) - Android (issue identified) - Browser (no issue found) I am facing a known problem without a suitabl ...

Looking for advice on using the ternary operator in your code? Let us

In my JS file, the code $scope.button = id ? "Edit" : "Add"; is functioning correctly. I am trying to implement it in the View like this: <button name="saveBtn" class="btn btn-primary" tabindex="10">{{person.id ? 'Edit' : 'Add&ap ...

Sending form data after a successful AJAX request with jQuery in ASP.NET MVC 5

Within my Asp.net MVC 5 project, there exists a form equipped with a Submit button. Upon clicking this Submit button, the following tasks are to be executed: Client-side validation must occur using jQuery on various fields (ensuring required fields are ...

AngularJS Gallery Showcase

Trying to showcase a collection of videos in a modal using angular.js, I decided to implement the solution from . However, I encountered difficulty in integrating my scope variables into the "html5gallery" class. <div class="html5gallery" data-skin="ho ...

Problem with Jquery show/hide feature only resolved after refreshing the page

I built a checkout page that consists of three fieldsets with unique IDs - 1, 2, and 3. I want the page to initially display only fieldset 1 while hiding fieldsets 2 and 3. Here is the jQuery code I used: $(document).ready(function(){ $("#1").show(); ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Creating an interactive checkbox input field utilizing a JSON-driven database

Can someone assist me with creating dynamic checkboxes? I have JSON data structured as follows: [ { "categoryName": "Category 1", "items": [ { "value": "value1", "label": "label1" }, { "value": "value2" ...