Angular JS with Require JS - angularjs

I am using requireJs with Angular Js , Into my require-config file i bootstrapped the application as follows:
require([
'angular',
'app'
], function(angular, app) {
// alert('sd');
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
// bootstrap the app manually
angular.bootstrap(document, ['iStickers']);
alert('test');
});
}
when I am trying to use the function to change language in my application,
'use strict';
define([
'angular',
'angularRoute',
// 'resource'
], function(angular) {
alert('ww');
var loginModule = angular.module('iStickers.login',['ngRoute','ngResource'])
loginModule.service('translationService',[ function($resource) {
alert('3');
this.getTranslation = function($scope, language) {
var languageFilePath = 'translation_' + language + '.json';
console.log(languageFilePath);
$resource(languageFilePath).get(function(data) {
$scope.translation = data;
});
};
}]);
loginModule.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'views/login/login.html',
controller: 'loginCtrl'
});
}])
loginModule.controller('loginCtrl', 'translationService', ['$scope', function($scope, translationService) {
$scope.selectedLanguage = 'no';
$scope.translate();
}]);
it gives me an error:
Error: [ng:areq] Argument 'loginCtrl' is not a function, got string
http://errors.angularjs.org/1.3.8/ng/areq?p0=loginCtrl&p1=not%20a%20function%2C%20got%20string
minErr/<#https://code.angularjs.org/1.3.8/angular.js:63:12

Related

Angularjs Ionic controller error

I am working with IONIC Framework (Angularjs)
I am receiving below error,
463788 error Error: [ng:areq] http://errors.angularjs.org/1.4.3/ng/areq?p0=PaymentCtrl&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at http://localhost:8100/lib/ionic/js/angular/angular.min.js:6:416
at Sb (http://localhost:8100/lib/ionic/js/angular/angular.min.js:22:18)
at Qa (http://localhost:8100/lib/ionic/js/angular/angular.min.js:22:105)
at http://localhost:8100/lib/ionic/js/angular/angular.min.js:79:497
at I.appendViewElement (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:4463)
at Object.O.render (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:16:17590)
at Object.O.init (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:16:16825)
at I.render (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:3419)
at I.register (http://localhost:8100/lib/ionic/js/ionic-angular.min.js:17:3150)
Here is my code for controller.
define(['ionic', 'ionicAngular', 'angular',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular) {
'use strict';
console.log('Payment controller ');
var PaymentCtrl = function ($scope, PaymentSvc,$state, $ionicLoading) {
/*$scope.phoneNumberVerification = function() { $state,$ionicPopup,
console.log('PhoneNumber controller added1 ');
$ionicLoading.hide();
$state.go('tab.eateries');
};*/
// When button is clicked, the popup will be shown...
};
return PaymentCtrl;
});
Serveics.js
define(['ionic', 'ionicAngular', 'angular',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular) {
'use strict';
//console.log('service modules');
var PaymentSvc = function(){
console.log('serverices call');//var svc = this;
}
return PaymentSvc;
});
// });*/
payment.js
define(['ionic', 'ionicAngular', 'angular',
'./modules/payment/controllers/paymentctrl',
'./modules/payment/services/services',
'ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter'],
function (ionic, ionicAngular, angular,
paymentCtrl,
paymentSvc) {
'use strict';
console.log('payment.js modules');
var payment = angular.module('payment', ['ionic'])
.controller('PaymentCtrl', paymentCtrl)
.service('PaymentSvc',paymentSvc);
return payment;
});
No need to inject ['angular','ngRoute', 'angularAnimate', 'angularSanitize', 'uiRouter']. Ionic automatically inject angular decencies when you inject ['ionic']
Just write your controller directly
angular.module('starter', ['ionic']).controller('PayCtrl',function ($scope,$state,$ionicLoading,PaymentSvc){
//starter is the app name come from ng-app="starter"
$ionicLoading.show();
$scope.phoneNumberVerification = function(){
console.log('PhoneNumber controller added1');
$ionicLoading.hide();
$state.go('tab.eateries');
};
});
I advise you to organize your javascript project files to in 3 files:
app.js which contains
angular.module('starter', ['ionic', 'starter.controllers','starter.services'])..config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
}).state('app.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/home.html',
controller : 'HomeCtrl'
}
}
});
$urlRouterProvider.otherwise('/app/home');
});
controller.js which contains your controllers
angular.module('starter.controllers', []).controller('AppCtrl', function('PayCtrl',function ($scope,$state,$ionicLoading,PaymentSvc){
$ionicLoading.show();
$scope.phoneNumberVerification = function(){
console.log('PhoneNumber controller added1');
$ionicLoading.hide();
$state.go('tab.eateries');
};
});
service.js which contains you connections to server
angular.module('starter.services', []).factory('PaymentSvc',function($http,$q){
});
it is an injection error. for example, if you inject ['a','b','c'] you must have it in your function in the same order and amount: function(a,b,c). in your case, you have more parameters in the injection than the parameters in your controller function.

Karma test failed when I inject a ui-router resolve in a controller

I've been trying to test my controller:
app.js
angular
.module('MyModule', [
'ui.router'
]);
angular
.module('MyModule')
.config(configFn);
configFn.$inject = ['$stateProvider'];
function configFn($stateProvider){
$stateProvider
.state('myState',{
url:'state',
views: {
'main' : {
templateUrl: 'src/views/view.html',
controller: 'MyCtrl',
controllerAs: 'ctrl',
resolve: {
DataResolve: ['MyService', function(MyService){
return MyService.getData();
}]
}
}
}
});
controller.js
angular
.module('MyModule')
.controller('MyCtrl', Controller);
Controller.$inject = ['DataResolve'];
/* #ngInject */
function Controller(DataResolve) {
var vm = this;
vm.data = DataResolve;
}
My spec
controller_spec.js
describe('Controller', function(){
beforeEach(module('MyModule'));
beforeEach(inject(function($controller){
this.myCtrl = $controller('MyCtrl');
}));
it('Controller should be defined', function() {
expect(this.myCtrl).toBeDefined();
});
});
But when the test runs, I get the following error:
Error: [$injector:unpr] Unknown provider: DataResolveProvider <- DataResolve <- MyCtrl
What I have been doing wrong?
In your beforeEach, add a reference to your service :
beforeEach(inject(function($controller, DataResolve){
this.DataResolve = DataResolve;
this.myCtrl = $controller('ParcelasController', {
DataResolve: this.DataResolve;
});
}));

i am trying to test my angular controller using jasmine. But i am getting Error: [$injector:modulerr]

following is the code from my sample angular project.
app.js code:
(function () {
'use strict';
var app = angular.module('actorsDetails', [
// Angular modules
'ngResource',
// 3rd Party Modules
'ui.bootstrap',
'ui.router'
]);
app.config(['$stateProvider', '$urlRouterProvider', configRoutes]);
function configRoutes($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'app/home/home.html',
controller: 'HomeCtrl',
controllerAs: 'vm'
})
.state('form', {
url: '/form',
templateUrl: 'app/form/form.html',
controller: 'FormCtrl',
controllerAs: 'vm',
resolve: {
initialData: ['actorApi', function (actorApi) {
return actorApi.getActorsResource();
}]
}
})
.state('resource', {
url: '/resource',
templateUrl: 'app/resource/resource.html',
controller: 'ResourceCtrl',
controllerAs: 'vm',
resolve: {
initialData: ['actorApi', function (actorApi) {
return actorApi.getActorsResource();
}]
}
});
$urlRouterProvider.otherwise('/main');
}
app.run(['$state', function ($state) {
// Include $route to kick start the router.
}]);
})();
controller code:
(function () {
'use strict';
angular.module('actorsDetails').controller('HomeCtrl', HomeCtrl);
/* #ngInject */
function HomeCtrl($state) {
/* jshint validthis: true */
var vm = this;
vm.activate = activate;
vm.test = true;
vm.navigate = navigate;
activate();
function activate() {
}
function navigate() {
$state.go('form');
}
}
})();
**test.js**
describe('HomeCtrl', function() {
beforeEach(module('actorsDetails'));
beforeEach(inject(function ($rootScope, $controller) {
var scope = $rootScope.$new();
var HomeCtrl = $controller('HomeCtrl', {
$scope: scope
});
}));
it('should have a HomeCtrl controller', function() {
expect(true).toBeDefined();
});
});
there are the files I have included in my karma.config.js
I have added all the angularJS dependent files.
I have also added the controller file that i need to test
files: [
'src/lib/angular/angular.min.js',
'src/lib/angular-mocks/angular-mocks.js',
'src/lib/angular-resource/angular-resource.min.js',
'src/lib/angular-route/angular-route.min.js',
'src/app/app.js',
'src/app/home/home.controller.js',
'src/test/specs/*.js'
],
kindly pinpoint me, what is that I am doing wrong...
Mock out the $state object in your unit test.
var mockState = { go: function() {} };
var HomeCtrl = $controller('HomeCtrl', { $scope: scope, $state: mockState });
The $injector:modulerr is most likely related to your use of $state in your controller. Instead of mocking, you could try adding the library to your karma config, and loading the module in your unit test.
'src/lib/angular-ui-router/release/angular-ui-router.min.js'
beforeEach(module('ui.router'));

How can I access a service in a ui-router resolve?

I have an Angular Application app.js :
var app;
app = angular.module('app',
[
'exam',
'ui.router'
])
.controller('appController', AppController)
.service('examService', ExamService));
and I have a config file:
var stateConfig = [
'$locationProvider',
'$sceDelegateProvider',
'$sceProvider',
'$stateProvider',
'examService',
function ($locationProvider, $sceDelegateProvider, $sceProvider, $stateProvider, examService) {
$locationProvider.html5Mode(true);
$sceProvider.enabled(false);
var exams = {
name: 'exams',
url: '/Exams',
templateUrl: 'app/exams/partials/home.html',
resolve: {
exams: examService.getAdminExams()
}
};
$stateProvider.state(exams);
}];
app.config(stateConfig);
Can someone give me some advice.
When I run this it tells me:
Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error:
[$injector:unpr]
Unknown provider: examService
http://errors.angularjs.org/1.3.7/$injector/unpr?p0=examService
I checked and my examService is declared before the other two files:
<script src="/app/appController.js"></script>
<script src="/app/services/ExamService.js"></script>
<script src="/app/app.js"></script>
<script src="/app/appConfig.js"></script>
<script src="/app/appRun.js"></script>
Also in my controller I use the examService and it's available without any problem.
Here's what my controller looks like:
var AppController = (function () {
function AppController($scope, $state, es) {
var _this = this;
this.$scope = $scope;
this.$state = $state;
this.es = es;
}
AppController.$inject = [
'$scope',
'$state',
'examService'
];
return AppController;
})();
You can only inject providers to config block. Try injecting $injector and use it to get your examService:
var stateConfig = [
'$locationProvider',
'$sceDelegateProvider',
'$sceProvider',
'$stateProvider',
'$injector',
function ($locationProvider, $sceDelegateProvider, $sceProvider, $stateProvider, $injector) {
$locationProvider.html5Mode(true);
$sceProvider.enabled(false);
var exams = {
name: 'exams',
url: '/Exams',
templateUrl: 'app/exams/partials/home.html',
resolve: {
exams: function() {
//retrieve your service
var examService = $injector.get('examService');
return examService.getAdminExams()
}
}
};
$stateProvider.state(exams);
}];
Or according to the docs, you can inject directly like this:
resolve: {
exams: function(examService) {
return examService.getAdminExams();
}
}
This may not work if you minify the script. Try this:
resolve: {
exams: ['examService',function(examService) {
return examService.getAdminExams();
}]
}

Angularjs MVC application, I cannot figure out why I'm getting an Unknown provider: $routeProvider <- $route

I'm working on an application that is using angularjs routing. I've added ngRoute as a dependancy, I have confirmed that the angular-route.js file is being loaded. I still get an unknown provider error $routeProvided <- $route.
What am I missing?
I have three files for my app, they are loaded in the order displayed below.
My application.js file
(function () {
'use strict';
var app = angular.module('MyApp', [
// Angular modules
'ngAnimate', // animations
'ngRoute', // routing
]);
app.run(['$route', '$rootScope', '$q', 'routemediator',
function ($route, $rootScope, $q, routemediator) {
routemediator.setRoutingHandlers();
}]);
})();
my route config file
(function () {
'use strict';
var app = angular.module('MyApp');
// Configure Toastr
toastr.options.timeOut = 4000;
toastr.options.positionClass = 'toast-bottom-right';
var events = {
controllerActivateSuccess: 'controller.activateSuccess',
spinnerToggle: 'spinner.toggle'
};
var config = {
appErrorPrefix: '[Error] ', //Configure the exceptionHandler decorator
docTitle: 'error: ',
events: events,
version: '1.0.0'
};
app.value('config', config);
app.config(['$logProvider', function ($logProvider) {
// turn debugging off/on (no info or warn)
if ($logProvider.debugEnabled) {
$logProvider.debugEnabled(true);
}
}]);
app.config(['commonConfigProvider', function (cfg) {
cfg.config.controllerActivateSuccessEvent = config.events.controllerActivateSuccess;
cfg.config.spinnerToggleEvent = config.events.spinnerToggle;
}]);
})();
My config file
(function () {
'use strict';
var app = angular.module('MyApp');
// Collect the routes
app.constant('routes', getRoutes());
// Configure the routes and route resolvers
app.config(['$routeProvider', 'routes', routeConfigurator]);
function routeConfigurator($routeProvider, routes) {
alert('in route config');
routes.forEach(function (r) {
$routeProvider.when(r.url, r.config);
});
$routeProvider.otherwise({ redirectTo: '/Home.html' });
}
// Define the routes
function getRoutes() {
return [
{
url: '/',
config: {
title: 'Home',
templateUrl: '/App/views/Home.html',
controller: 'HomeController',
controllerAs: 'vm',
settings: {
nav: 1,
content: '<i class="fa fa-dashboard"></i> Home'
}
}
}
];
}
})();
If you're using a recent verison of Angular (1.2+), you need to download and include the ngRoute file in addition to angular.js, which doesn't include all these side providers anymore.

Resources