Angular factory undefined in controller - javascript

I am working on a very simple factory to be used inside an angular controller. The problem is that the factory doesn't seem to be getting picked up inside the controller. The console.log returns undefined and I can't seem to figure out why.
var app = angular.module('App', ['ngRoute', 'ngTouch']);
app.controller('AppController', [
'$scope',
'$rootScope',
'myFactory',
function($scope, $routeParams, myFactory) {
console.log(myFactory)
}]);
app.factory('myFactory', function() {
return 'test';
});

The problem is that your controller is is injecting $rootScope and then you change it to $routeParams in the function. Have a look at this fiddle http://jsfiddle.net/wkqajL2x/6/ where I have removed those two attributes. It then works fine.
var app = angular.module('App', []);
app.controller('AppController', [
'$scope',
'myFactory',
function($scope, myFactory) {
console.log(myFactory)
}]);
app.factory('myFactory', function() {
return 'test';
});
so you just need to decide which one out of those you really want to use.

Related

Why my Angular factory throw TypeError: __tracer.traceFunCall(...) is not a function

This line of code does no let me sleep:
$scope.search = function (login) {
github.getUser(login).then(onUserResponse, onError);
};
Loading it up:
angular.module('lol')
.factory('github', github);
Returning two functions :
return {
getUser: getUser,
getRepos: getRepos
};
With this siganture:
var github = function ($http) {
Consumed by MainController:
var MainCtrl = function ($scope, github, $filter, $timeout, $intervel, $anchorScroll, $location) {
And not injected into it's dependencies:
MainCtrl.$inject = ['$scope', '$filter', '$interval', '$timeout', '$anchorScroll', '$location'];
With the app being loaded like this:
angular.module('lol', [])
.controller('MainCtrl', MainCtrl);
And all of this throw: TypeError: __tracer.traceFunCall(...) is not a function
i think you missed githubas second parameter in MainCtrl.$inject = ['$scope', 'github'...
also updated your jsbin here
code organization was complicating situation more than necesary.
Also from the looks of it you tried to do two modules quick example how it should be done here.

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) {...}

Read JSON with Angular, undefined service

I am trying to read a JSON data from a file using angular factory and service. But Angular can't see my defined service. Here is my factory:
//jsonService.js
angular.module('jsonService', ['ngResource'])
.factory('JsonService', function($resource) {
alert($resource)
return $resource('example.json',{}, {
getData: {method:'GET', isArray: false}
});
});
And my controller:
//app.js
'use strict';
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'jsonService'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]).
controller('mainController', ['JsonService', function($scope, JsonService){
JsonService.getData(function(data) {
console.log("Test");
$scope.length = data.length;
})}]);
And I get:
"Error: JsonService is undefined"
You're injecting 'JsonService' as the first parameter of your function, but you are using the JsonService as the 2nd parameter of your function.
Should be ['JsonService', '$scope', function($scope, JsonService){ or if $scope not needed then ['JsonService', function(JsonService){
This line in app.js should look like
controller('mainController', ['$scope','JsonService', function($scope, JsonService){

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: Having trouble restructuring

Here is the current (Working) way i have my angular app.
app.js
require('angular');
require('angular-ui-router');
var listStoresCtrl = require('./controllers/store/listStoresCtrl');
var createStoreCtrl = require('./controllers/store/createStoreCtrl.js');
var storeDetailsCtrl = require('./controllers/store/storeDetailsCtrl.js');
var listDepartmentsCtrl = require('./controllers/dept/listDepartmentsCtrl');
var createDepartmentCtrl = require('./controllers/dept/createDepartmentCtrl.js');
//-- init angular js
var ngApp = angular.module('ngApp', ['ui.router'], function($interpolateProvider){
//-- as the output conflicts with blade lets alter the defaults
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}).config(['$stateProvider','$logProvider','$urlRouterProvider', function ($stateProvider, $logProvider,$urlRouterProvider) {
//-- enable logging
$logProvider.debugEnabled(true);
}]);
ngApp.controller('listStoresCtrl', ['$scope', 'Store', '$log', listStoresCtrl]);
ngApp.controller('createStoreCtrl', ['$scope', '$log', 'Store', '$rootScope', '$timeout','ManagerService', createStoreCtrl]);
ngApp.controller('storeDetailsCtrl', ['$scope', '$log', '$rootScope', 'Store', storeDetailsCtrl]);
ngApp.controller('listDepartmentsCtrl', ['$scope', 'Department', '$log', listDepartmentsCtrl]);
ngApp.controller('createDepartmentCtrl', ['$scope', '$log', 'Department', '$rootScope', '$timeout','ManagerService', createDepartmentCtrl]);
//-- stick it all together and kick it off
angular.bootstrap(document, ['ngApp']);
BUT i would like to restructure this so that my Store ctrls etc and Department ctrls are within their own module.
EG: storeCtrls.js
angular.module('storeCtrls', [])
.controller('listStoresCtrl', ['$scope', 'Store', '$log', listStoresCtrl])
.controller('createStoreCtrl', ['$scope', '$log', 'Store', '$rootScope', '$timeout','ManagerService', createStoreCtrl])
.controller('storeDetailsCtrl', ['$scope', '$log', '$rootScope', 'Store', storeDetailsCtrl]);
Then in the app.js file call them in like so.
require('./controllers/storeCtrls');
angular.module('ngApp', ['storeCtrls'], function($interpolateProvider){...}
But for some reason this does not work I am get getting an error of Uncaught object.
Bit of relevant history on this:
I am using Gulp and Browserify to do my JS.
My listStoresCtrl for example are using the
module.exports = function(scope, Store, log){...}
method to return them.
UPDATE
i seem to have sorted the Uncaught object, as i was missing the ['ui.router'] with the call to
angular.module('ngApp', ['storeCtrls']...
so it should be
angular.module('ngApp', ['ui.router', 'storeCtrls']..
Now to get the rest to link up...
Seems the main issue was i was not injecting some items that i simply removed and forgot to re-add.
I simply must of copied over this injection ['ui.router'] with the call to
angular.module('ngApp', ['storeCtrls']...
where i should have been adding as well below:
angular.module('ngApp', ['ui.router', 'storeCtrls']..
Now to get the rest to link up...

Categories