Not Sure why but my controller wont recognize the service. I have checked enerything what am I missing here. I have included the services file in HTML. It recognizes other services but not just this one
(function() {
'use strict';
angular
.module('pollyvotes')
.service('lineChart', lineChart);
/** #ngInject */
function lineChart($scope, $http){
var promise = null;
return function(){
if (promise){
return promise
} else {
promise = $http.jsonp('')
.success(function(data){
$scope.predictions = data;
})
.error( function(data){
$scope.data = "Request failed";
})
return promise;
}
}
Controller
(function() {
'use strict';
angular
.module('pollyvotes')
.controller('MainController', MainController);
/** #ngInject */
function MainController($scope, $timeout, lineChart) {
$scope.photos = [ {id: 'chart-1', name: 'something here',src: "assets/images/300x600.png", href: "https://www.google.de/?gws_rd=ssl", discription: "say something about the chart here"},
{id: 'chart-2', name: 'another picture', src: "assets/images/300x600.png", href: "https://www.google.de/?gws_rd=ssl", discription: "say something about the chart here"},
{id: 'chart-3', name: 'another picture', src: "assets/images/300x600.png", href: "https://www.google.de/?gws_rd=ssl", discription: "say something about the chart here"},
{id: 'chart-4', name: 'another picture', src: "assets/images/300x600.png", href: "https://www.google.de/?gws_rd=ssl", discription: "say something about the chart here"}
];
}
})();
and declaring module
(function() {
'use strict';
angular
.module('pollyvotes', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize',
'ngMessages', 'ngAria', 'ngResource', 'ui.router',
'ui.bootstrap', 'akoenig.deckgrid', 'smoothScroll',
'ngToast', 'picardy.fontawesome']);
})();
You are injecting $scope to your service.
That's what the documentation says about this error:
https://docs.angularjs.org/error/$injector/unpr
Attempting to inject a scope object into anything that's not a controller or
a directive, for example a service, will also throw an
Unknown provider: $scopeProvider <- $scope error.
There is a good answer how to avoid this here:
Injecting $scope into an angular service function()
Related
I have the following component in which I am trying to inject a service:
angular.
module('phoneList').
component('phoneList', {
templateUrl: '/static/common/angular/phone-list/phone-list.template.html',
controller: ['$http', 'authenticationService',
function PhoneListController($http, authenticationService) {
var self = this;
authenticationService.authenticate().then(function(){
console.log('it worked!!!!!!!!');
});
}
]
});
The service looks like this:
angular.module('authentication').factory('authenticationService', function($http, $se){
function authenticate(){
$http.post('/o/token/', data, config)
.success(function (data, status, headers, config) {
console.log('auth service: '+data['access_token']);
$sessionStorage.access_token = data['access_token'];
});
}
function getToken(){
return $sessionStorage.access_token;
}
return {
authenticate:authenticate,
getToken:getToken
};
});
My phone-list.module.js looks like this:
angular.module('phonecatApp', [
'phoneList',
'authentication',
]);
angular.module('phoneList', ['authentication']);
When I run this i get the error:
Uncaught ReferenceError: authenticationService is not defined
When I put 'authenticationService' in '', I get the error:
Error [$injector:unpr] authtenticationService
It seems the service isn't properly injected into the PhoneListController.
Change it to:
controller: ['$http', 'authenticationService',
function PhoneListController($http, authenticationService) {
...
The strings in the array are just to keep the injected dependency references minification safe. The service still needs to be added as a function argument.
Also be sure to call angular.module once for each component:
app.module.js
angular.module('phonecatApp', [
'ngRoute',
'phoneList',
'authentication',
]);
phone-list.module.js
angular.module('phoneList', ['authentication']);
I need help, been searching and thinking for hours but didn't come up with a good solution. I am experiencing error "Expected undefined to be defined" which is repeatedly occurs when I call $scope in my It() functions.
Spec.js
describe("C0001Controller", function(){
var $scope,
$rootScope,
$injector,
$controller,
$httpBackend,
$loading,
C0001Controller;
describe("initialize controllers",function(){
beforeEach(function(){
angular.module('app.c0001App');
})
beforeEach(inject(function(_$rootScope_, _$injector_, _$controller_, _$httpBackend_, _$loading_)
{
$rootScope = _$rootScope_;
$injector = _$injector_;
$controller = _$controller_;
$httpBackend = _$httpBackend_;
$loading = _$loading_;
$scope = $rootScope;
C0001Controller = $controller('C0001Controller', {
$scope: $scope,
$loading : $loading
});
}));
});
it("should use the user ",function(){
var languages = [{id: "en", name: "English"}, {id: "jp", name: "Japanese"}];
expect(languages).toBeDefined();
it("should read if there are languages used", function(){
expect($scope).toBeDefined();
});
describe("checking connection to module and controller", function(){
it("should be connected to module", function(){
expect("app.c0001App.C0001Controller").toBeDefined();
});
it("contains C0001Spec Spec", function(){
expect(true).toBe(true);
});
it("should be equal to user", function(){
var user = {};
var c0001Data = user;
expect(c0001Data).toBe(user);
});
});
});
I was thinking if the format I did in the karma.conf.js file has a mistake.
// list of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'app/*.js',
'tests/*.js'
],
here's my Controller.js
angular.module('app.c0001App', [
'ui.router'
])
.config(function($stateProvider) {
$stateProvider.state('/c0001', {
url : '/c0001'
, templateUrl : 'pages/C0001.html'
, data : {
pageTitle: 'LOGIN'
}
});
})
.controller('C0001Controller', function ($rootScope, $scope, $http, $window, $location, $loading) {
var promise = $http.get('changeLanguage.do?lang=en');
promise.success(function(data, status, headers, config) {
//some codes here
Thank you in advance.
This question already has answers here:
Angular Unit Test Unknown provider: $scopeProvider
(2 answers)
Closed 7 years ago.
Yet another question about injecting $scope into tests and services :-) Learning angular and using angular-seed application as a start.
I have extended my controller to have $scope but now my default angular seed tests are failing with
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope
I don't understand is the error with my controller or with my tests...
View/Controller/Service
(function () {
"use strict";
angular.module("app.view1", ["ngRoute"])
.config(["$routeProvider",
function ($routeProvider) {
$routeProvider.when("/view1", {
templateUrl: "views/view1/view1.html",
controller: "View1Ctrl"
});
}
])
.factory("User", ["$http",
function ($http) {
var User = {};
User.get = function () {
return $http.get("/api/v1/user");
};
return User;
}
])
.controller("View1Ctrl", ["$scope", "User",
function ($scope, User) {
User.get().success(
function (response) {
$scope.user = response;
});
}
]);
}());
Test
'use strict';
describe('app.view1 module', function() {
beforeEach(module('app.view1'));
describe('view1 controller', function(){
it('should ....', inject(function($controller) {
//spec body
var view1Ctrl = $controller('View1Ctrl');
expect(view1Ctrl).toBeDefined();
}));
});
});
Application is working and I get to see data in HTML but tests are failing... all suggestions welcome!
I was missing $scope in the test, here is updated test that works:
'use strict';
describe('app.view1 module', function() {
beforeEach(module('app.view1'));
describe('view1 controller', function() {
it('should ....', inject(function($controller, $rootScope) {
//spec body
var $scope = $rootScope.$new(),
ctrl = $controller('View1Ctrl', {
$scope: $scope,
$User: {}
});
expect(ctrl).toBeDefined();
}));
});
});
Your are in a test, there is no DOM, and no $scope.
Your can deal with this by passing locals to the $controller service, like this :
var $scope = {};
var view1Ctrl = $controller('View1Ctrl', { $scope: $scope });
I am following the Book Angular.js - Novice to Ninja
This is how I have set up the project:
app/js/app.js:
angular.module('blogger', ['blogger.posts', 'ui.router']);
app/modules/posts/postModule.js:
angular.module('blogger.posts', ['blogger.posts.controllers', 'blogger.posts.services']);
angular.module('blogger.posts').config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider){
$urlRouterProvider.otherwise('/posts');
$stateProvider.state('allPosts', {
url:'/posts',
templateUrl:'modules/posts/views/posts.html',
controller:'PostsController'
});
}]);
app/modules/posts/js/controllers.js:
angular.module('blogger.posts.controllers')
.controller('PostController', ['$scope', 'postService', function($scope, postService){
$scope.getAllPosts=function(){
return postService.getAll();
};
$scope.posts=$scope.getAllPosts();
}]);
app/modules/posts/js/services.js:
angular.module('blogger.posts.services').factory('postService',
function(){
return {
posts:[{
id:1,
title:'Sample title 1',
content:'Sample content 1',
permalink:'sample-title1',
author:'Sandy',
datePublished:'2015-21-01'
}],
getAll:function(){
return this.posts;
}
}
});
But if I run the code it is giving me this error:
Error: [$injector:nomod] Module 'blogger.posts.controllers' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument
/**
* Create blogger.posts which dependes on sub modules
* 'blogger.posts.controllers', 'blogger.posts.services'
* Ex . angular.module('moduleName', []) syntax for module setter.
* This is requried before registering on module
*/
angular.module('blogger.posts', ['blogger.posts.controllers',
'blogger.posts.services']);
/**
* Module setters
*/
angular.module('blogger.posts.controllers', []);
angular.module('blogger.posts.services', []);
/**
* Now you can register controllers , service, directive etc
*/
angular.module('blogger.posts.services').factory('postService',
function () {
return {
posts: [{
id: 1,
title: 'Sample title 1',
content: 'Sample content 1',
permalink: 'sample-title1',
author: 'Sandy',
datePublished: '2015-21-01'
}],
getAll: function () {
return this.posts;
}
}
});
angular.module('blogger.posts.controllers')
.controller('PostController', ['$scope', 'postService',
function ($scope, postService) {
$scope.getAllPosts = function () {
return postService.getAll();
};
$scope.posts = $scope.getAllPosts();
}]);
I just fixed this (i was doing the same tutorial :P). in the file app/js/app.js you need to have:
angular.module('blogger', [
'ui.router',
'blogger',
'blogger.posts'
]).run(['$state', function($state){
$state.go('allPosts');
}]);
and that should fix it :)
Please can anyone explain why the following throws an "Argument 'MainCtrl' is not a function, got undefined" error which seems to be tied into the use of module dependency injection with directives(?!).
angular.module('app', [])
.controller('MainCtrl', [function() {
var self = this;
self.name = "will this work";
self.items = [
{
name: "name 1",
test: "test 1"
},
{
name: "name 2",
test: "test 2"
}
];
}]);
angular.module('app',[])
.directive('typeahead', [function() {
return {
templateUrl: 'type-ahead.html',
restrict: 'AEC',
scope: {
items: '=',
prompt: '#',
title: '#',
subtitle: '#',
model: '=',
onSelect: '&'
}, <...more code>
Yet it will work perfectly fine when I remove the
[ ]
module dependency braces from the directive to read
angular.module('app').directive('typeahead', ...)
It also works perfectly fine if I define the directive as a cascade following the controller definition i.e.
angular.module('app', [])
.controller('MainCtrl', [function() {
var self = this;
self.name = "will this work";
self.items = [
{
name: "name 1",
test: "test 1"
},
{
name: "name 2",
test: "test 2"
}
];
}])
.directive('typeahead', [function() {
return {
Thanks in advance!
You are running into Angular's Creation versus Retrieval Problem:
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.
The first time you run angular.module('app',[]), Angular will create a module called app. Next time, you only need to run angular.module('app'), Angular will try to load the existing module app.
Since you call angular.module('app',[]) once again, module app has been re-initialized. That's why MainCtrl is undefined now.