Angular Factory "Cannot read property 'property' of undefined - javascript

Using Angular 1.6.x
Having a really hard time getting a Factory to work with a login submit
login.controller.js
angular.module('appName').controller('LoginController',[
'$scope',
function($scope, Login){
$scope.submitLogin = function(){
console.log('login requested');
Login.login();
}
}]);
login.factory.js
angular.module('appName').factory('Login', function (){
var service = {};
service.login = function(){
console.log('Login Factory');
}
return service;
});
The error I'm getting is TypeError: Cannot read property 'login' of undefined
From all the examples I've looked at I'm injecting the factory into the controller, created an object in the factory, and returning that object back. What am I missing here?
Another question to is why am I unable to include the factory in my controller via?
angular.module('appName').controller('LoginController',[
'$scope',
Login, // <<<<<< This throws an error (scripts.min.js:1 Uncaught ReferenceError: Login is not defined)
function($scope, Login){
$scope.submitLogin = function(){
console.log('login requested');
Login.login();
}
}]);
The reason I'm injecting this way is to eliminate the possibilities of errors during minification.
Edit
Question answered with injecting Factory with Quotes.
angular.module('appName').controller('LoginController',[
'$scope',
'Login', // <<<< Was not using quotes
function($scope, Login){
$scope.submitLogin = function(){
console.log('login requested');
Login.login();
}
}]);

You have to inject Login factory and wrap it within quotes 'Login':
'$scope', 'Login',
function($scope, Login){

angular.module('appName').controller('LoginController',[
'$scope',
'Login', // <<<<<< you should inject within quotes
$scope.submitLogin = function(){
console.log('login requested');
Login.login();
}
}]);

You need to enclose the factoryName within single quotes
angular.module('appName').controller('LoginController',[
'$scope',
'Login', // Change hereReferenceError: Login is not defined)
function($scope, Login){
$scope.submitLogin = function(){
console.log('login requested');
Login.login();
}
}]);

It should be, You are missing ''
angular.module('appName').controller('LoginController',[
'$scope',
'Login',
function($scope, Login){
}]);

Also note that the order of your injections with quotes needs to be consistent with the parameters. For example, the following will still give you an undefined:
angular.module('appName').controller('LoginController',
['$scope', 'Factory1', 'Factory2',
function($scope, Factory2, Factory1){
Factory1.something; // undefined
Factory2.something; // undefined
}]);
You need follow the sequence, like this:
angular.module('appName').controller('LoginController',
['$scope', 'Factory1', 'Factory2',
function($scope, Factory1, Factory2){
Factory1.something; // Yay!
Factory2.something; // Woohoo!
}]);

Related

Trouble passing angular resolve values into controller

How do I pass the resolve validToken value to my controller?
Config:
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/recover/:token', {
templateUrl: 'recover.html',
controller: 'recoverCtrl',
resolve: {
validToken : function(){
return "INVALID TOKEN"
}
}
});
}])
Controller:
.controller('recoverCtrl', ['$location','$scope','$http', '$routeParams', '$rootScope',
function($location,$scope,$http,$routeParams,$rootScope,validToken) {
console.log(validToken);
// Rest of controller code.
}
]);
I would like to do this without removing the []'s so the code could eventually be minifed. The below example is working as I expected so I know that all of my code it working, I'm just not sure what I should add to the above code to make it function similarly.
.controller('recoverCtrl', function($location,$scope,$http,$routeParams,$rootScope,validToken) {
console.log(validToken);
//Other code
});
Figured it out thanks to Etsus.
I just needed to add the object key as a string while injecting and it was able to determine that it was a resolve key
.controller('recoverCtrl', ['$location','$scope','$http', '$routeParams', '$rootScope', 'validToken', function ($location, $scope, $http, $routeParams, rootScope, validToken) {
console.log(validToken);
}]);

Angular factory function throwing error claiming it isn't a function in Controller

I have seen a couple of questions like this before but they are usually clearly missing injections, and hopefully that isn't the case with my problem.
As part of my app I am making I am trying to make a get request to the server to return a list of modules.
Controller
app.controller('ModulesCtrl', ['$scope','modFact','quizIndexFactory', '$http', function($scope, $http, quizIndexFactory, modFact){
$scope.moduleSet;
$scope.status;
getModules();
function getModules(){
modFact.getList()
.then(function (response) {
$scope.moduleSet = response.data;
}, function (error) {
$scope.status = 'unable to load modules in controller: ' + error.message;
});
}
Factory
app.factory('modFact', ['$http', function($http){
var modFact = {};
modFact.getList = function() {
console.log("success");
return $http.get('http://localhost:3000/module');
};
return modFact;
}]);
Yet I get the error pointing to the function call in the controller:
Error: modFact.getList is not a function
Any ideas? I am following the structure provided by this blog post:
http://weblogs.asp.net/dwahlin/using-an-angularjs-factory-to-interact-with-a-restful-service
It seems that the order of arguments being injected into the controller does not match the order that you supply the arguments. In your controller, the entity that is named modFact is actually angular's $http service (which doesn't have a getList method).
(Taking a little liberty with indentation and newlines to demonstrate the problem):
[ '$scope','modFact','quizIndexFactory', '$http',
function($scope, $http, quizIndexFactory, modFact) {
...
}]
should be:
[ '$scope', '$http', 'quizIndexFactory', 'modFact',
function($scope, $http, quizIndexFactory, modFact) {
...
}]

ReferenceError: $state is not defined

I have a rails application which use AngularJS and I have a problem, the problem is that I want redirect to a certain state after a form is submited, but in the chrome's console I have a ReferenceError: $state is not defined and nothing happens.
This is my controller.
angular.module('myapp')
.controller('CreatePollCtrl', ['$scope', 'Restangular', '$state',
function($scope, Restangular) {
$scope.addPoll = function() {
if ($scope.allow_anonymous_answer == null)
$scope.allow_anonymous_answer = false
var poll = {title: $scope.title, description: $scope.description, allow_anonymous_answer: $scope.allow_anonymous_answer, initial_message: $scope.initial_message, final_message: $scope.final_message};
Restangular.all('polls').post(poll).then(function(response) {
$state.go('dashboard');
});
};
}]);
What can I do?, is $state correctly injected?
you forgot add $state to function()
angular.module('myapp')
.controller('CreatePollCtrl', ['$scope', 'Restangular', '$state',
function($scope, Restangular, $state) {
Add $state as a parameter to your function, like $scope.addPoll = function($state) {...}

AngularJS: '$scope is not defined'

I keep getting '$scope is not defined' console errors for this controller code in AngularJS:
angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
function($scope, $routeParams, $location, Authentication, Articles){
$scope.authentication = Authentication;
}
]);
$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Where in my AngularJS MVC files should I be looking at to find problems with the $scope not being defined properly?
For others who land here from Google, you'll get this error if you forget the quotes around $scope when you're annotating the function for minification.
Error
app.controller('myCtrl', [$scope, function($scope) {
...
}]);
Happy Angular
app.controller('myCtrl', ['$scope', function($scope) {
...
}]);
Place that code inside controller:-
angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
function($scope, $routeParams, $location, Authentication, Articles){
$scope.authentication = Authentication;
$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
}
]);
Just put you $scope.create function inside your controller. Not outside !
$scope is only defined in controllers, each controller have its own. So write $scope outside your controller can't work.
Check scope variable declared after controller defined.
Eg:
var app = angular.module('myApp','');
app.controller('customersCtrl', function($scope, $http) {
//define scope variable here.
});
Check defined range of controller in view page.
Eg:
<div ng-controller="mycontroller">
//scope variable used inside these blocks
<div>

Angularjs Getting error when trying to call method from a service i defined

I'm learning Angularjs and i'm trying to create a service to do common tasks that need to be done for all my controllers.
I'm currently getting the error:
TypeError: Cannot call method 'getAuthHeader' of undefined
app.js
var token = "mytoken"
var baseUrl = "mybaseUrl";
var myezteam = angular.module('myezteam', ['ui.bootstrap']);
myapp.config(function($routeProvider) {
$routeProvider
.when('/profile',
{
controller: 'ProfileController',
templateUrl: 'template.html'
})
.otherwise({redirectTo: '/profile'});
});
// This gets the basic information that is needed for every page
myapp.service('base', function() {
this.getAuthHeader = function($http) {
// Set authorization token so we know the user has logged in.
return $http.defaults.headers.common.Authorization = 'Bearer ' + token;
}
});
profile.js
myapp.controller('ProfileController', ['$scope', '$http', function($scope, $http, base) {
base.getAuthHeader($http); // <-- THIS LINE IS THROWING THE ERROR
}]);
Why is the error occurring and how can I fix it? Also, is there a way to setup a config on my app so that I don't need to call base.getAuthHeader($http); in every controller, but it will automatically get called when every controller is loaded?
You're not injecting your service base into your controller. You need to inject it in the same way you did with $scope and $http
myapp.controller('ProfileController', ['$scope', '$http', 'base',
function($scope, $http, base) { ... });

Categories