AngualrJS - Module - Controller Access Issue - javascript

I have an issue communicating from my application to a module i have created. I have create an AngularJS module below.
(function (document, window) {
'use strict';
var piCart = angular.module('piCart', []);
piCart.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/cart', {
templateUrl: "packages/pi-cart/segments/cart.html",
controller: 'CartController',
private : true
}).
when('/checkout', {
template: "Checkout Page",
// controller: 'CartController',
private : true
});
}]);
piCart.factory('TestFactory', function(){
return{
test : function(){
return 'test works';
}
}
});
piCart.controller("CartController",function(TestFactory){
console.log("Cart Controller Running");
console.log(TestFactory.test());
});
})(document, window);
This is loaded into my main application as so
var app = angular.module('app', ['ngRoute', "ui.bootstrap", "googlechart", "piCart"]);
Im trying to call the module TestFactory from the app.controller like so
app.controller('ProductController',function($scope){
$scope.addToCart = function(id){
//alert("clicked: "+id);
test = TestFactory.test();
console.log(test);
};
});
But im getting the error
ReferenceError: TestFactory is not defined

I believe you're getting that error because you did not inject TestFactory in the controller:
app.controller('ProductController', function($scope, TestFactory) {
// your code...
});

Related

unable to inject a service in controller

I am using requireJS for my angularjs app.
common.service.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.config(['$provide', function ($provide) {
$provide.factory("CommonService", CommonService);
}]);
CommonService.$inject = ["$http", "$q", "$window"];
function CommonService($http, $q, $window) {
var service = {};
service.sharedValue;
return service;
}
});
page1.controller.js
define(function () {
var coreModule = angular.module('coreModule');
coreModule.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
// Q2: common service
$scope.commonService = CommonService;
}]);
});
Now When I am running my app, it throws me below error:
Error: [$injector:unpr] Unknown provider: CommonServiceProvider <- CommonService <- Page1Controller
any inputs?
Your core module should have empty dependencies injected
var coreModule = angular.module('coreModule',[]);
Also in page1. controller you dont have to declare the module again, you can just use
angular.module('coreModule')
.controller('Page1Controller', ['$scope', "CommonService", function ($scope, CommonService) {
Define config
Define the service
Define the controller, inject the service, use the dependency in function declaration etc. As you would know, both are needed, after all you need the those handles, else what's the point in injecting.
Define a module, define module dependencies. NOTE that the service has to be defined before controller. If you reverse the order, you will get an error, probably that's what is happening here. Without full code, I can't tell.
bootstrap angular.
Finally working plunkr: http://plnkr.co/edit/CE9enkgW3KASx8pf5vdb?p=preview
define('config',[],function(){
function config($routeProvider) {
$routeProvider.when('/home', {templateUrl: 'tpl.home.html', controller: 'HomeController'})
.otherwise({redirectTo: '/home'});
}
config.$inject=['$routeProvider'];
return config;
});
define('dataSvc',[], function(app){
function factoryFunc ($q, $timeout){
var svc = {getData: getData};
return svc;
function getData() {
console.log('executing function');
var d = $q.defer();
$timeout(function(){
console.log("firing timeout");
d.resolve({name:"test", data:[1, 2, 3, 4]});
}, 750);
return d.promise;
}
}
factoryFunc.$inject=['$q', '$timeout'];
return factoryFunc;
});
define('HomeController',[], function() {
function HomeController($scope, dataSvc) {
$scope.name = "Mahesh";
dataSvc.getData().then(function(result){
$scope.data=result;
console.log($scope.data);
});
}
HomeController.$inject=['$scope','dataSvc'];
return HomeController;
});
define('coreModule', ['config', 'dataSvc', 'HomeController']
, function(config, dataSvc, HomeController){
var app = angular.module('app', ['ngRoute','ngResource']);
app.config(config);
app.factory('dataSvc',dataSvc);
app.controller('HomeController', HomeController);
});
require(['coreModule'],
function() {
angular.bootstrap(document, ['app']);
}
);
Refer also,
https://www.sitepoint.com/using-requirejs-angularjs-applications/
http://beletsky.net/2013/11/using-angular-dot-js-with-require-dot-js.html

Angularjs controller not working, throws error (newbie)

i'm working with angular-seed project.
I'm trying to retreive data from mysql database.
I need to know how to define different controller for each view.
For example, I have this structure:
js
|_modules
|_companies
|_controller.js
|_data.js
|_app.js
|_base.js
I have added this route to app.js
.state('app.companies', {
url: '/companies',
title: 'Companies',
templateUrl: helper.basepath('companies.html'),
controller: 'companiesCtrl' //THIS THROWS THE ERROR BELOW
})
companies.html has scripts added to botom of the page
<script src="app/js/modules/companies/data.js"></script>
<script src="app/js/modules/companies/controller.js"></script>
and this is the code for controller.js (also tested the commented part)
(function() {
'use strict';
angular
.module('appname')
.controller('companiesCtrl', companiesCtrl);
companiesCtrl.$inject = ['$scope','companiesData','$log'];
function companiesCtrl($scope, companiesData, $log) {
console.log('asd'); //NEVER REACH THIS LOG
};
});
/*var app = angular
.module('appname')
.controller('companiesCtrl', ['$scope','companiesData','$log', function($scope, companiesData, $log){
console.log('asd'); //NEVER REACH THIS LOG
$scope.companies = {};
Data.get('companies').then(function(data){
$scope.companies = data.data;
console.log('($scope.companies)');
});
}]);
*/
But I keep getting
Error: [ng:areq] Argument 'companiesCtrl' is not a function, got undefined
Same if I script ng-controller="companiesCtrl" on my view.
change your function to:
(function() {
'use strict';
angular
.module('appname')
.controller('companiesCtrl', companiesCtrl);
companiesCtrl.$inject = ['$scope','companiesData','$log'];
function companiesCtrl($scope, companiesData, $log) {
console.log('asd'); //NEVER REACH THIS LOG
};
})();// execute this function then it will work
See this example if you remove () breaket then it will give you the error.
If possible then create controller like this:
angular.module('appname')
.controller('companiesCtrl', ['$scope', function($scope) {
console.log('asd'); //NEVER REACH THIS LOG
}]);
Please change your controller as :
(function() {
'use strict';
function companiesCtrl($scope, companiesData, $log) {
console.log('asd'); //NEVER REACH THIS LOG
};
angular
.module('appname')
.controller('companiesCtrl', companiesCtrl);
companiesCtrl.$inject = ['$scope','companiesData','$log'];
})();
The problem was on script loading.
I had to use lazy loading of the files within my app.js
Here's the code:
app.js companies route
.state('app.companies', {
url: '/companies',
title: 'Companies',
templateUrl: helper.basepath('companies.html'),
resolve: helper.resolveFor('companiesCtrl'),
controller: 'companiesCtrl'
})
lazy load code
.constant('APP_REQUIRES', {
scripts: {
'modernizr': ['vendor/modernizr/modernizr.custom.js'],
'icons': ['vendor/fontawesome/css/font-awesome.min.css',
'vendor/simple-line-icons/css/simple-line-icons.css'],
'companiesCtrl': ['app/js/modules/companies/data.js','app/js/modules/companies/controller.js']
},
modules: []
});

How do you add a service in Angular so a controller can use it?

I have a basic angular setup. I want to add another factory service so that the mainCtrl can use it.
Here is my controller.js
angular.module('Manalator.controllers', [])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Here is my services.js
angular.module('Manalator.services', [])
.factory('cordovaReady', [function () {
return function (fn) {
var queue = [],
impl = function () {
queue.push([].slice.call(arguments));
};
document.addEventListener('deviceready', function () {
queue.forEach(function (args) {
fn.apply(this, args);
});
impl = fn;
}, false);
return function () {
return impl.apply(this, arguments);
};
};
}])
.factory('manaFactory', [function(){
this.testString = function(){
return 'This works';
};
}]);
Here is my routes.js
angular.module('Manalator', ['ngRoute', 'Manalator.services', 'Manalator.controllers'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/main.html'
})
.when('/devotion', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/devotion.html'
})
.when('/results', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/results.html'
})
.otherwise({redirectTo: '/'});
});
I get the following error:
TypeError: Cannot read property 'testy' of undefined
at new <anonymous> (controllers.js:3)
at Object.i [as invoke] (main.min.js:1)
at $get.f.instance (main.min.js:2)
at m (main.min.js:1)
at s (main.min.js:1)
at $get.e (main.min.js:1)
at main.min.js:1
at p.$get.p.$eval (main.min.js:3)
at p.$get.p.$apply (main.min.js:3)
at main.min.js:1
It is a cordova phonegap setup with basic routes. I am new to angular. I have looked over the internet and im having trouble setting up a basic service to hold all my data so i can access it from all my routes. Any help would be appreciated.
You will need to identify your services as a dependency of the controller.
The first step is to make sure you define the services before the controller.
then change the controller code so that it names the services as a dependency.
angular.module('Manalator.controllers', ['Manalator.services'])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Hope this helps!

Injecting angular controller in jasmine

I have read through many examples in regards to injecting controllers into a jasmine unit test, however I keep getting "Error: [ng:areq] http://errors.angularjs.org/undefined/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined".
Here is my code:
main.spec.js:
'use strict'
describe("Testing Main Controller", function(){
var scope, controller;
var dummyFunction = function(){};
var defaultDocument = {
_id: "123456"
};
beforeEach(module('app.controllers'));
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('MainCtrl', {
$scope: scope,
SearchService: dummyFunction,
ResultsService: dummyFunction,
FacetService: dummyFunction,
EsDateService: dummyFunction,
Likes: dummyFunction,
Bookmarks: dummyFunction
});
}));
describe("Likes", function(){
it('shall give the user the ability to like a document that is currently being displayed.', function(){
scope.updateLike([defaultDocument]);
expect(defaultDocument.isLiked).toBe(true);
});
it('shall give the user the ability to remove a like from a document that is currently being displayed.', function(){
defaultDocument.isLiked = true;
scope.updateLike([defaultDocument]);
expect(defaultDocument.isLiked).toBe(true);
});
});
});
main_controller.js:
'use strict';
angular.module('app.controllers')
.controller('MainCtrl', function($scope, SearchService, ResultsService, FacetService, EsDateService, Likes, Bookmarks) {
});
app.js:
angular.module('app.services', ['ngResource', 'elasticjs.service']);
angular.module('app.controllers', [ 'app.services']);
var app = angular.module('app', [
'ui.bootstrap',
'elasticjs.service',
'app.services',
'app.controllers',
'app.config',
'facet.directives',
'ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
controller: 'SearchCtrl',
templateUrl: 'views/search/search.html'
})
.when('/journal', {
controller: 'JournalCtrl',
templateUrl: 'views/journal/journal.html'
})
.otherwise({
redirectTo: '/'
});
}
]);
app.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix("!");
}
]);
When I attach MainCtrl to app rather than app.controllers it seems to find MainCtrl. What am I doing wrong?
You don't need to re-declare dependencies for app module, as app module injects app.controllers
beforeEach(module('app'));
Quick example how it can be solved - http://jsfiddle.net/PtXFb/

Error: Unknown provider: SessionProvider <- Session AngularJS

I am aware that the error which is in the title of this question is basically because in my controller I am injecting a Session service in my controller that has not been defined. I am currently looking at: Angular Devise for which I am rolling out in an application that is using rails but have angular and rails separate. My setup on the angular side is as followed:
main.js
angular.module('App.controllers', []);
angular.module('App.config', []);
angular.module('App.directives', [])
angular.module('App.resources', ['ngResource']);
angular.module('App.services', []);
var App = angular.module("App", [
"ngResource",
"ngCookies",
"$strap.directives",
"App.services",
"App.directives",
"App.resources",
"App.controllers",
"TotemApp.config"
], function ($routeProvider, $locationProvider, $httpProvider) {
var interceptor = ['$rootScope', '$q', function (scope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
window.location = "/login";
return;
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
});
Session.js
App.service('Session',[ '$cookieStore', 'UserSession', 'UserRegistration', function($cookieStore, UserSession, UserRegistration) {
this.currentUser = function() {
return $cookieStore.get('_angular_devise_user');
}
this.signedIn = function() {
return !!this.currentUser();
}
this.signedOut = function() {
return !this.signedIn();
}
this.userSession = new UserSession( { email:"sample#email.com", password:"password", remember_me:true } );
this.userRegistration = new UserRegistration( { email:"sample#email.com", password:"password", password_confirmation:"password" } );
}]);
sessions_controller
App.controller('SessionsController', ['$scope', '$location', '$cookieStore', 'Session', function($scope, $location, $cookieStore, Session) {
$scope.session = Session.userSession;
$scope.create = function() {
if ( Session.signedOut ) {
$scope.session.$save().success(function(data, status, headers, config) {
$cookieStore.put('_angular_devise_user', Session.userSession.email);
$location.path('/todos');
});
}
};
$scope.destroy = function() {
$cookieStore.remove('_angular_devise_user');
$scope.session.$destroy();
};
}]);
routes.js
'use strict';
App.config(function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main/home.html',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'views/sessions/new.html',
controller: 'SessionsController'
})
.when('/sign_up', {
templateUrl: 'views/registrations/new.html',
controller: 'RegistrationsController'
})
.otherwise({
redirectTo: '/'
});
});
This error occurs when I try to access the login page or register page. If someone can shed some light that would be greatly appreciated. Not entirely sure how to resolve this Error: Unknown provider: $SessionProvider <- $Session error
At first glance this looks correct. I can only assume that perhaps you've not included Session.js in your index.html file?
Angular clearly doesn't know what 'Session' service is so there's something wrong there either file not loaded, not loaded correctly or something along those lines as far as I can see.
Edit: Does the error say 'SessionProvider <- Session' or '$SessionProvider -< $session' because if it's the latter, then something is named wrong somewhere in your app since your service is named 'Session' not '$Session'.
When you have syntax error in other javascript or typescript files. You will get the same error. Please make sure that you have no syntax error.

Categories

Resources