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

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();
}]
}

Related

Angular JS with Require JS

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

Uncaught Error - Injector modulerr in my angularjs web application

I try to do a demo of charts. I get uncaught modulerr. I am not able to solve this issue. Please let me know where I am wrong.
Note :
I have run bower install and I have the libraries injected to the module under /public/lib folder.
My index.jade
doctype html
html(lang='en', xmlns='http://www.w3.org/1999/xhtml', xmlns:fb='https://www.facebook.com/2008/fbml', itemscope='itemscope', itemtype='http://schema.org/Product')
head
block header
block stylesheet
link(rel='stylesheet', href='/semantic/semantic.min.css')
link(rel='stylesheet', href='/css/vendor.min.css')
block headerscript
script(type='text/javascript', src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js")
script(type='text/javascript', src='//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js')
script(type='text/javascript', src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js')
body(ng-init="compare='hellovar'")
.ui.grid
.ui.computer.tablet.only.fitted.row
.column
.ui.menu
.item
a.ui.green.button(href="/")
| Chart Demo
.ui.mobile.only.three.column.inverted.black.fitted.row
.column.floated.left.inverted
.ui.menu.fluid.two.item.inverted
header.item
a.ui.green.icon.button(href="/")
i.content.icon
.column
| Alasql Demo
.column.right.aligned
.fitted.row
.column
block content
div(ui-view)
block footer
script(type='text/javascript').
angular.element(document).ready(function() {
angular.bootstrap(document, ['home.core']);
});
My controller part
'use strict';
angular.module('home.core',['ngRoute']);
angular.module('home.core')
.controller('home.core.controller', ['$rootScope', '$scope', '$window',
function($rootScope, $scope, $window) {
console.log("inside home core controller");
function _init() {
console.log("Inside Home Controller");
}
_init();
}
]);
angular.module('home.core')
.config(
["$stateProvider", "$urlRouterProvider",
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state("home-core", {
url: '/',
templateUrl: 'partials/home/core/index.html',
controller : 'home.core.controller'
});
}
]);
angular.module('home.core')
.factory('home.core.service', ['Restangular',
function(Restangular) {
var restAngular = Restangular.withConfig(function(Configurer) {
Configurer.setBaseUrl('/api/ecommerce');
});
return {
create: restAngular.all('')
.post
}
}
]);
I get the below error when I run the web app
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=home.core&p1=Error…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.min.js%3A17%3A381
Firstly, I don't see where you are running the restangular script:
<script src="js/lib/restangular.min.js"></script>
Second, is all of your Angular code in one file? You first have to inject restangular into your main module. Can you try changing your code to this:
'use strict';
angular.module('home.core',['ngRoute','restangular'])
.controller('home.core.controller', ['$rootScope', '$scope', '$window',
function($rootScope, $scope, $window) {
console.log("inside home core controller");
function _init() {
console.log("Inside Home Controller");
}
_init();
}
])
.config(
['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state("home-core", {
url: '/',
templateUrl: 'partials/home/core/index.html',
controller : 'home.core.controller'
});
}
])
.factory('home.core.service', ['Restangular',
function(Restangular) {
var restAngular = Restangular.withConfig(function(Configurer) {
Configurer.setBaseUrl('/api/ecommerce');
});
return {
create: restAngular.all('')
.post
}
}
])

Restangular ignores setBaseUrl

The app runs on http://domain1 an must request data from http://domain2 with the following code:
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'restangular'
]);
myApp.config(['$routeProvider', 'RestangularProvider', function($routeProvider, RestangularProvider) {
$routeProvider.when('/view1', {
templateUrl: '/view1.html',
controller: 'View1Ctrl'
});
$routeProvider.otherwise({redirectTo: '/view1'});
RestangularProvider.setBaseUrl("http://domain2/");
}]);
var rest = null;
myApp.controller('View1Ctrl', ['$scope', 'Restangular', function($scope, Restangular) {
rest = Restangular;
var cursos = Restangular.one("resource",100).get()
}]);
Nonetheless, the request goes to http://domain1. What is going on? I also inspected the Restangular configuration, by putting Restangular in the global scope, as the rest variable, and the base url seems is property set.
Hey you can create a factory and use different domain to get data something like below
(function () {
'use strict';
angular.module('app')
.factory('Domain2Restangular', ['Restangular', Domain2RestangularFunction]);
function Domain2RestangularFunction( Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
var baseURL = 'http://domain2';
RestangularConfigurer.setBaseUrl(baseURL);
RestangularConfigurer.setDefaultHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });
});
}
}());
You can invoke
return Domain2Restangular.all('')
.post(data)
.then(function(response) {
return response;
}, function(error) {
return error
});

In angular js, how do I show angular-loading bar with ui-router and ocLazyLoad

Problem : I am not able to load the angular-loading-bar using lazy load and ui.route.
Am I missing something ?
This is how my config.lazlyload.js file looks like :
// lazyload config
angular.module('app')
// oclazyload config
.config(['$ocLazyLoadProvider',
function($ocLazyLoadProvider) {
// We configure ocLazyLoad to use the lib script.js as the async loader
$ocLazyLoadProvider.config({
debug: false,
events: true,
modules: [{
name: 'ngGrid',
files: [
'vendor/modules/ng-grid/ng-grid.min.js',
'vendor/modules/ng-grid/ng-grid.min.css',
'vendor/modules/ng-grid/theme.css'
]
}, {
name: 'angular-loading-bar',
files: [
'vendor/modules/angular-loading-bar/loading-bar.min.js',
'vendor/modules/angular-loading-bar/loading-bar.min.css'
]
}]
});
}
]);
This is my config.router.js :
'use strict';
/**
* Config for the router
*/
angular.module('app')
.run(
['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]
)
.config(
['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.otherwise('/access/signin');
$stateProvider
.state('access.test', {
url: '/test/me',
templateUrl: 'tpl/test.html',
controller: 'testController',
resolve: {
deps: ['$ocLazyLoad',
function($ocLazyLoad) {
return $ocLazyLoad.load('ui.select', 'angular-loading-bar').then(
function() {
return $ocLazyLoad.load('js/controllers/test.js');
}
);
}
]
}
})
}
]
);
My controller is :
'use strict';
/* Controllers */
app.controller('testController', ['$scope', '$http', '$state', '$stateParams',
function($scope, $http, $state, $stateParams) {
//assuming this should start the loader
$scope.start();
var path = 'js/app/largeJson.json';
var mails = $http.get(path).then(function(resp) {
return resp;
//this shall end the loader
$scope.complete()
});
}
]);
You complete function will never get called because you returned a data then you wrote $scope.complete(), you should write that $scope.complete() function before returning data.
CODE
app.controller('testController', ['$scope', '$http', '$state', '$stateParams',
function($scope, $http, $state, $stateParams) {
//assuming this should start the loader
$scope.start();
var path = 'js/app/largeJson.json';
var mails = $http.get(path).then(function(resp) {
//this shall end the loader
$scope.complete();
return resp;
});
}
]);
Update
if you wish to use the loading bar without the interceptor, you can do that as well. Simply include the loading bar service as a dependency instead of the main angular-loading-bar module:
angular.module('myApp', ['cfp.loadingBar'])
Then your controller will have the start & complete methods which will internally call cfpLoadingBar methods
Controller
app.controller('testController', ['$scope', '$http', '$state', '$stateParams', cfpLoadingBar,
function($scope, $http, $state, $stateParams, cfpLoadingBar) {
$scope.start = function() {
cfpLoadingBar.start();
};
$scope.complete = function () {
cfpLoadingBar.complete();
};
//assuming this should start the loader
$scope.start();
var path = 'js/app/largeJson.json';
var mails = $http.get(path).then(function(resp) {
//this shall end the loader
$scope.complete();
return resp;
});
}
]);
For more info take a look at Github page
Hope this could help you, Thanks.

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