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.