Unable to inject $location service - angularjs

This code gives me Error: [$injector:unpr] Unknown provider: $scope, $locationProvider <- $scope, $location.
var app = angular.module('myApp.controllers', []);
app.controller('Signup', ['$scope, $location', function($scope, $location) {
$scope.checkEmailValid = function(){
//TODO make a decision about whether to go somewhere, if true do this:
$location.path('/view2');
};
}]);
Am I missing something about how to inject the location service?
I haven't configured $locationProvider, but doing so doesn't seem to help.

You forgot the quotes around $scope and $location :
var app = angular.module('myApp.controllers', []);
app.controller('Signup', ['$scope', '$location', function($scope, $location) {
$scope.checkEmailValid = function(){
//TODO make a decision about whether to go somewhere, if true do this:
$location.path('/view2');
};
}]);
This should to the trick !

Try simpler form (without array form - probably missing quote is your problem):
app.controller('Signup', function($scope, $location) {
$scope.checkEmailValid = function(){
//TODO make a decision about whether to go somewhere, if true do this:
$location.path('/view2');
};
});
Minification can be solved in build time using ngMin and this form is less error prone and more readable

Related

Angular: How to resolve [$injector:unpr] error for $httpProvider and inject controller in jasmine test

I am new to angular testing. Facing some issues while testing angular code using jasmine.
It will be highly appreciated if you read my question and try to solve my problem as i googled it but could not find any satisfactory solution
Here is my angular app
var app = angular.module('myApp', ['ngAnimate', 'ui.router', 'ui.bootstrap', 'toggle-switch',
'ngTagsInput', 'blockUI', 'ngBootbox', 'ui.select', 'ngSanitize', 'angular.filter']);
app.config(["$httpProvider", "blockUIConfig", function ($httpProvider, blockUIConfig) {
'use strict';
blockUIConfig.autoBlock = false;
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.interceptors.push('interceptorService');
}]);
And here is controller file:
app.controller('myController', ['$scope', '$filter', '$http', '$window', '$ngBootbox', '$modal', 'dataservice', 'user', 'message_kinds',
function($scope, $filter, $http, $window, $bB, $modal, dataservice, user, message_kinds) {
$scope.user = user;
/controller logic/
}]);
I want to test this controller if $scope.user equals to user or not.Am using jasmine for testing. Here is spec file.
describe("myController", function() {
beforeEach(module('myApp'));
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe("myController testing", function () {
it("should update scope.user", function () {
var user = {customer_id: 1};
var my_controller = $controller('myController', { user: user });
expect(my_controller.user).toEqual(user);
});
});
});
I have also included all dependency files like angular.js, angular-mocks.js etc in SpecRunner.html
Having three problems:
Facing [$injector:unpr] http://errors.angularjs.org/1.4.4/$injector/unpr?p0=interceptorServiceProvide error on app.config block regarding $httpProvider
ReferenceError: $controller is not defined in spec.js at line
var my_controller = $controller('myController', { user: user });
How can I test if scope.user is equals to user in expect block?
1) Check this answer, as regards $http/$httpBackend which might help you - you can adapt this to get the answers you're looking for
2) Have you declared $controller (and now $httpProvider) as a variable in the beginning of the describe() block?
3) You should have that already. Your code, at least as I can see, looks like it should work like you want it to.

AngularJS Ionic: Unable to inject Ionic History

I am trying to inject ionic history in my Ionic Project and I am getting this error
Error: [$injector:unpr] http://errors.angularjs.org/1.2.14/$injector/unpr?p0=%24ionicHistoryProvider%20%3C-%20%24ionicHistory
This is my complete controller code
.controller('menu', ['$scope', '$state', '$ionicHistory', function($scope,$state,$ionicHistory) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}])
Please what am doing wrong.
Are you using Cordova?
If you are, it is probably happening because you did not inject ngCordova in your module.
Like:
angular.module('anotei', ['ionic', 'ngCordova'])
my friend your problem is not in you $ionicHistory, it is in the locatStorage. you are not injecting the local storage in the controller. Just inject it and it will work.
Cheers.
Try to add the closing curly bracket } for the $scope.gotoLogouts function, just before the last line.
#Nadeem Khoury you should not inject localStorage. It is $localStorage that should be injected but he is using localStorage which should not be injected.
If this is exactly the code you are using, I am with #Ennedigi
.controller('menu', ['$scope', '$state', '$ionicHistory', function($scope,$state,$ionicHistory) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}
}])
try to include timeout, location and windows in module
IonicModule
.factory('$ionicHistory', [
'$rootScope',
'$state',
'$location',
'$window',
'$timeout',
'$ionicViewSwitcher',
'$ionicNavViewDelegate',
function($rootScope, $state, $location, $window, $timeout, $ionicViewSwitcher, $ionicNavViewDelegate) {
#Blaze, you have to inject $localStorage in your controller like below,
.controller('menu', ['$scope', '$state', '$ionicHistory', '$localStorage' function($scope,$state,$ionicHistory,$localStorage) { //first menu
var user = JSON.parse(localStorage.getItem("user"));
$scope.gotoUser = function(){
localStorage.removeItem("selectedName");
localStorage.setItem("selectedName",username);
$state.go("Page");
};
$scope.gotoLogouts = function() {
// localStorage.clear();
$ionicHistory.clearHistory();
//localStorage.removeItem('user');
$state.go("login");
}
}])

Angular's $interval service not found when testing using karma and mocha

I created a service that has $interval as a dependency and makes use of it and seems to work. Unfortunately when I'm trying to unit test the app $interval service is not found by angular:
Unknown provider: $$qProvider <- $$q <- $interval
I am not calling the service inside a controller as usual, but on the run() method of the app:
app.service('myService', ['$rootScope', '$window', '$interval', myService]);
app.run(function (myService) {
...
});
It works, but if I try to test the app crashes. Rest of angular services don't seem to have this problem ($window, $location, $rootScope, ...) and even this same service works if I attach my service to a controller instead than calling it at app.run():
app.controller('myController', ['myService', function(myService){ ... }]);
I use Karma+Mocha+Sinon+Chai to test.
UPDATE
Example with mini app trying to use $interval at app.run():
var anApp = angular.module('myTestApp', ['ngRoute']);
anApp.run(function($rootScope, $timeout, $window, $location, $interval) {
// blah
});
The test:
describe("Lalarala", function() {
var scope = null;
beforeEach(function() {
module("myTestApp");
inject(function ($rootScope) {
scope = $rootScope.$new();
});
});
it("doesnt crash", function () {
//blah
});
});
Note: If you remove $interval from the app.run() it works. Instead, other angular services like $timeout, $window or $location don't seem to bother.
Also, I've noticed that other services like $resource have this problem too.
I presume some of those services require something else to be there before they are ready and that's why I can't call them at app.run()?
Thanks for any help.
This line is definitely wrong.
app.controller('myController', [myService, function(myService){ ... }]);
Array injection syntax should contain strings
app.controller('myController', ['myService', function(myService){ ... }]);
Ok,
After checking many things I found the problem had to do with an angular-mocks being out of date.
I updated versions of angular and angular-mocks and now everything is working fine.
Sorry!

Can't access my service in my controller (undefined)

I am trying to create a service to do some AJAX requests.
However, my service keeps getting undefined when I try to do something with it in my controllers. Here is my code.
I have found a lot of examples on here, and I've tried to follow a lot of them but no matter what I do my service keeps getting undefined.
My service:
MyApp.factory('myService', function($http) {
return {
findAll: function() {
return $http.get('/findAll')
.then(function(result) {
return result.data;
});
}
}
});
My Controller:
MyApp.controller('UserController', ['$scope', '$http', 'myService', function($scope, $http, $log, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
}]);
I assume I don't inject it correctly but I can't see whats wrong. I'm fairly new to Angular so..
Any pointers would be appreciated.
Remove $log from the injection. You are currently "naming" the myService service to $log and therefore myService inside the controller is undefined.
MyApp.controller('UserController', ['$scope', '$http', 'myService',
function($scope, $http, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
}]);
2nd solution
To avoid having to "name" the services like this it's acceptable to inject them without naming them.
MyApp.controller('UserController', function($scope, $http, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
});
Just remember to remove the closing bracket aswell.

AngularJs $scope undefined when controllers are inside a module

I'm trying to use the angular-seed template with the default settings. In controllers.js I use
angular.module('myApp.controllers', []).
controller('MyCtrl1', [function($scope) {
$scope.test = 'scope found!';
}])
.controller('MyCtrl2', [function() {
}]);
There the $scope is always undefined.
When I take the controller out of the module and register it globally it works fine. As here:
function MyCtrl1($scope) {
$scope.test = "scope found!";
}
MyCtrl1.$inject = ['$scope'];
Could someone explain to me why this is?
You cannot mix things like that. You need to decide on one of the two possibilities:
app = angular.module('test', []);
// possibility 1 - this is not safe for minification because changing the name
// of $scope will break Angular's dependency injection
app.controller('MyController1', function($scope) {
// ...
});
// possibility 2 - safe for minification, uses 'sc' as an alias for $scope
app.controller('MyController1', ['$scope', function(sc) {
// ...
}]);
I would not advise using the other syntax which declares Controller directly. Sooner or later with the growth of you app it will become hard to maintain and keep track. But if you must, there are 3 possibilities:
function myController1 = function($scope) {
// not safe for minification
}
function myController2 = ['$scope', function(sc) {
// safe for minification, you could even rename scope
}]
var myController3 = function(sc) {
// safe for minification, but might be hard
// to read if controller code gets longer
}
myController3.$inject = ['$scope'];
This is the proper way:
angular.module('myApp.controllers', []);
angular.module('myApp.controllers').controller('MyCtrl1', ['$scope', function($scope) {
}]);
I was also searching for that one, it seems that you need to type '$scope' before the function, as below:
angular.module('myApp.controllers', []).
controller('MyCtrl1', ['$scope', function($scope) {
$scope.test = 'scope found!';
}])
.controller('MyCtrl2', ['$scope',function() {
}]);
It kinda makes sense, I think it should be more clear though..
You can simply remove '[' and ']' when You are using $scope.
angular.module('myApp.controllers', []).
controller('MyCtrl1', function($scope) {
$scope.test = 'scope found!';
})
.controller('MyCtrl2', [
function() {
}
]);

Categories

Resources