Inject $rootscope into services module - javascript

How would I inject $rootscope into wenzey.services so it is accessible across my application?
(function () {
'use strict';
/**
*
*/
angular
.module('wenzey.services', '$rootScope', [])
$rootScope.type = "consumer";
})();
This is the error message I am currently getting:
Uncaught ReferenceError: $rootScope is not defined
Uncaught Error: [$injector:modulerr] Failed to instantiate module wenzey due to:
Error: [$injector:modulerr] Failed to instantiate module wenzey.services due to:
Error: [ng:areq] Argument 'modulesToLoad' is not an array

You are using wrong definition for a module. You are mixing a module with a service. You need to understand the below to use them properly:
You specify a module as a dependency of other module in module definition. E.g.
angular
.module('wenzy.services', [])
.factory('AppService', function () {
// Add methods
});
Now you can use the module wenzy.services as a dependency while defining module wenzy.controllers as below:
angular
.module('wenzy.controllers', ['wenzy.services']);
You inject a service in another service/ controller while defining the service/ controller . E.g. We have injected the service AppService in the AppController below
angular
.module('wenzy.controllers', ['wenzy.services'])
.controller('AppController', function (AppService) {
// Add controller defintion
})
The $rootScope is a service provided by angular and can be injected into any service/ controller. You don't need to add that as part of module definition.

Related

How would I include a non-existent module as a dependency in Angular tests?

I have inherited two angular apps. The one app(AppB) that I'm writing tests for and for lack of better phrasing it sets atop another app(AppB) that I've created. I want each of these to be their own separate repos with tests that cover that repo.
So I have a module with a controller that I want to test that looks something like this
angular.module('moduleName', ['moduleDependency1','moduleDependency2','moduleDependency3'])
Where moduleDependency2 is not included in the config because this particular code doesn't need to be tested in this module.
I have tried setting the following up to test this module
beforeEach(function() {
module('moduleName');
inject(function (_$rootScope_, _$controller_, _$q_) {
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$controller = _$controller_;
$q = _$q_;
});
});
however this returns:
Error: [$injector:modulerr] http://errors.angularjs.org/1.5.7/$injector/modulerr?p0=moduleName
I tried declaring each module dependency but the moduleDependency2 then threw an error about not being defined.
What am I missing here?

angular js injector module error

i am new to angular js i am trying to inject factory in a config ,but it shows module not found
factory code
var app=angular.module('app',['ui.router','angular-jwt','ngResource','angularValidator','satellizer']);
app.factory('AUTH_SERVICE', function ($auth,$state,$q) {
var auth={};
auth.isloggedin=function() {
var defer = $q.defer();
if($auth.isAuthenticated()){
defer.resolve();
}
else
{
$state.go('login');
defer.reject();
}
return defer.promise;
}
return auth;
});
config code is
app.config(['AUTH_SERVICE','$authProvider','$stateProvider', '$urlRouterProvider',function(AUTH_SERVICE,$stateProvider, $urlRouterProvider,$authProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home',{
url:'/',
templateUrl:'pages/home.html'
})
.state('login',{
url:'/login',
templateUrl:'pages/login.html',
controller:'loginCtrl'
})
.state('register',{
url:'/register',
templateUrl:'pages/register.html',
controller:'registerCtrl'
})
.state('dashboard',{
url:'/Dashboard',
templateUrl:'pages/dashboard.html',
controller:'dashctrl',
resolve:{
skiplogin: _skiplogin
}
})
function _skiplogin(AUTH_SERVICE){
return AUTH_SERVICEAUTH_SERVICE.isloggedin();
}
}]);
but it shows error
angular.js:38Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=app&p1=Error%3A%20%…ocalhost%2Faccoex%2Fbower_components%2Fangular%2Fangular.min.js%3A39%3A319)
You can't inject factory object in the app.config because it can't be sure they have been loaded correctly..
In the app.config you can only inject Consts and Providers.
From the documentation
A module is a collection of configuration and run blocks which get
applied to the application during the bootstrap process. In its
simplest form the module consist of collection of two kinds of blocks:
Configuration blocks - get executed during the provider registrations
and configuration phase. Only providers and constants can be injected
into configuration blocks. This is to prevent accidental instantiation
of services before they have been fully configured.
Run blocks - get executed after the injector is created and are used
to kickstart the application. Only instances and constants can be
injected into run blocks. This is to prevent further system
configuration during application run time.
Take a look to provider here where you can configure a service in your app.config.
you can't inject factory in config as it loads after config
angularjs application loads as follows:
Run
Config
Instantiate factory or service
Controller

Angular not rendering templates what is main and common

I was trying to get some angular code to work and it seems that i am not quite understanding some of the syntax.
var mainModule = angular.module('main', ['common']);
What is the importance of "main" is that specific to something?
What is "common"?
I DO reference the angular latest js and app.js in layout.cshtml
I do not get any errors in chrome console.
My index.cshtml looks like
<div data-ng-controller="indexViewModel">
<h1>{{ topic }}</h1>
here is my app.js
var mainModule = angular.module('main', ['common']);
mainModule.controller("indexViewModel", function (
$scope, $http, $q, $routeParams, $window, $location, viewModelHelper) {
var self = this;
$scope.topic = "Tasks";
$scope.author = "Tom";
console.log("test");
});
(function (myApp) {
var viewModelHelper = function (
$http, $q, $window, $location) {
var self = this;
return this;
};
myApp.viewModelHelper = viewModelHelper;
}(window.MyApp));
Update:
Yes, my body tag was missing ng-app
<body data-ng-app="main">
Now i get the error with angular 1.5.6
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module main due to:
Error: [$injector:modulerr] Failed to instantiate module common due to:
Error: [$injector:nomod] Module 'common' 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.
Update 2:
OK , i see I NEEDED to have common defined since i called it that:
var commonModule = angular.module('common', ['ngRoute']);
var mainModule = angular.module('main', ['common']);
HOWEVER, getting this error now
angular.js:13642 Error: [$injector:unpr] Unknown provider: viewModelHelperProvider <- viewModelHelper <- indexViewModel
http://errors.angularjs.org/1.5.6/$injector/unpr?p0=viewModelHelperProvider%20%3C-%20viewModelHelper%20%3C-%20indexViewModel
at angular.js:68
Update 3 FIXED
I needed to add in this factory code
commonModule.factory('viewModelHelper',
function ($http, $q, $window, $location) {
return MyApp.viewModelHelper(
$http, $q, $window, $location);
});
The ng-app directive tells AngularJS that this is the root element of the AngularJS application.
You can only have one ng-app directive in your HTML document. If more than one ng-app directive appears, the first appearance will be used.
So, in angular.module('main', ['common']), main is the value of ng-app directive and common is the dependency on which your module main depends.
Take an example of routing, we inject the dependency ngRoute in the angular.module for routing of application.
Syntax : angular.module('main', ['ngRoute'])
Here, main is depends on ngRoute because without ngRoute module angular can not perform routing.
angular.module('main', ['common']) - main is the name of your module - you will later use it in HTML as the value of ng-app, and ['common'] is another module that your module depends on.
Make sure you defined ng-app="main" in your html. this is the first thing you need to define before you declare any controller
make sure you include angular.js as a script in your html (<script src="path/to/angular.js"></script>)?

Component doesn't resolve injection of $scope (angular 1.3.16)

I have encountered a really weird error. I'm working on a project where we're using John Papa's AngularJS styleguide.
I have the following component-file, my-profile.component.js, attached to app.mymodule
my-profile.component.js
(function() {
'use strict';
angular
.module('app.mymodule')
.component('myProfile', { })
.controller('MyProfileController', myProfileController);
/*#ngInject*/
function myProfileController($scope) {
...
}
})();
The component is rendered using in my view file.
app.mymodule is defined in mymodule.module.js
mymodule.module.js
(function () {
'use strict';
angular
.module('app.mymodule', []);
})();
And app is defined in app.modules.js, where app.mymodule is set as an app dependency
app.modules.js
(function() {
'use strict';
angular
.module('app', [
...
'app.mymodule'
]);
})();
my-profile.component.js compiles to the following code
my-profile.component.js (compiled)
(function() {
'use strict';
angular
.module('app.mymodule')
.component('myProfile', { })
.controller('MyProfileController', myProfileController);
myProfileController.$inject = ['$scope'];
function myProfileController($scope) {
...
}
})();
But for some reason, angular fails to inject the $scope-service, or any other service I attempt to inject. It produces the following error:
Error: [$injector:unpr] Unknown provider: 1FilterProvider <- 1Filter
http://errors.angularjs.org/1.3.16/$injector/unpr?p0=1FilterProvider%20%3C-%201Filter
at REGEX_STRING_REGEXP (/layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7eNaNbundles%fjs%fvendor:63:12)
at /layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:4031:19
at Object.getService [as get] (/layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:4178:39)
at /layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:4036:45
at Object.getService [as get] (/layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:4178:39)
at $get [as $filter] (/layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:16705:24)
at Parser.filter (/layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:12234:19)
at Parser.filterChain (/layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:12228:19)
at Parser.primary (/layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:12079:22)
at Parser.unary (/layout/js/vendor/angularjs-1.3.16/angular.js?bundleVirtualPath=%7e%fbundles%fjs%fvendor:12374:19)
I have another component in the same folder, attached to the same module, where I can easily inject any service. It looks as follows:
(function () {
'use strict';
angular
.module('app.mymodule')
.component('loginView', { })
.controller('LoginViewController', loginViewController);
/*#ngInject*/
function loginViewController($scope, $location) {
...
}
})();
I really can't figure out what I'm doing wrong. I've spellchecked, doublechecked, started over on the component, attempted to $inject $scope on the controller manually, but to no avail.
Does anyone have a clue what's going on here? :)
EDIT
As rolandjitsu pointed out, it was a problem in my view-file. I had used ng-pattern wrongfully, but was mislead by my own inability to interpret angular console-errors and a 'mildly' misleading error description in the angular docs.
Yes, it seems like you are missing a service provider called 1Filter. Maybe a missing module or some files missing?
Note: It has nothing to do with the $scope, it should not fail because of that.

Angular dependencies and provider not available error

I am loading a file upload script I found on Github
<script type="text/javascript" src="{% static 'bower_components/angular-file-upload/angular-file-upload.min.js' %}"></script>
and have a data import module :
(function () {
'use strict';
angular
.module('TestSite.import', [
'TestSite.import.controllers'
]);
angular
.module('TestSite.import.controllers', ['angularFileUpload']);
})();
as well as a controller
(function () {
'use strict';
angular
.module('TestSite.import.controllers' , ['angularFileUpload'])
.controller('UploadController', UploadController);
UploadController.$inject = ['$scope','angularFileUpload'];
/**
* #namespace UploadController
*/
function UploadController($scope, FileUploader) {
$scope.uploader = new FileUploader();
};
})();
And I am getting an error
Error: [$injector:unpr] Unknown provider: angularFileUploadProvider <- angularFileUpload
I am confused about the module declaration and DI. Why do I need to declare the module TestSite.import.controllers twice? I am injecting the right dependencies (angularFileUpload) and still getting that error, also what is a provider and why cant angular find it?
Looks like you confused name of the file upload service. Correct dependency injection looks like this:
angular
.module('TestSite.import.controllers')
.controller('UploadController', UploadController);
UploadController.$inject = ['$scope', 'FileUploader'];
/**
* #namespace UploadController
*/
function UploadController($scope, FileUploader) {
$scope.uploader = new FileUploader();
};
Also note, that you don't have to redefine module TestSite.import.controllers. To access already registered module you need to use getter notation, meaning no dependency array as the second parameter:
.module('TestSite.import.controllers').controller(...);

Categories

Resources