In my Angular application I adding tracing functionality, which should work as separate plugin, so if script included into HTML Angular should create service and initialize (run) it. Plugin is service because it has mandatory dependency on $rootScope.
For implementation I select to use Angular factory, like (code is in myservice.js):
angular.module('app').factory('mysevice', ['$rootScope', '$interval', serviceFunc]);
function serviceFunc($rootScope, $interval) {
return {
run: function () { ... }
}
}
And now I have problem how to immediately initialize it. My solution is to enhance Angular app run function (code is in myservice.js):
window.app.run(['mysevice', function (srvc) {
srvc.run();
}]);
Where app defined in separate main app.js file like:
var app = window.app = angular.module('app', [...]);
app.run(['$state', 'breeze', ...,
function ($state, breeze, ...) { ..real initialization.. }
The code is working fine. Both main run and run for myservice calls are fine. The application together with the service are working well, but the code looks ugly, especially storing the app in the global window object and multicasting the run function.
Is there a better way to do Angular service and initialize it immediately after app starts with some other Angular services dependencies.
You can call angular.module('app').run(function(){...}). So you will not need a global variable anymore.
Example:
angular.module('app').run(['mysevice', srvc.run.bind(srvc)]);
Related
I have an angular 1.5 project with many modules and each module may depend on other modules. Trying to unit test say a controller which is part of a module I would do import the module like this:
angular.mock.module('SaidModule');
...then provide and inject its services where needed.
The problem is that SaidModule depends on AnotherModule1, AnotherModule2, AnotherModule3....
angular.module('SaidModule', ['AnotherModule1', 'AnotherModule2', 'AnotherModule3']);
So naturally when I call SaidModule the other modules are also invoked which is out of scope in terms of Unit testing
In the unit test I have tried the following solution
angular.module('AnotherModule1',[]);
angular.module('AnotherModule2',[]);
angular.module('AnotherModule3',[]);
angular.mock.module('SaidModule');
and although for the current unit test I have successfully decoupled the dependencies I have also destroyed
the actual AnotherModule1, AnotherModule2, AnotherModule3 so when its there turn to be unit tested they are
not even visible in the angular project which seems correct to me. as I am using angular.module to define a
new module which just happens to override the actual module.
This solution though is also suggested here mocking module dependencies
In the angular docs it states see angular docs mock module
If an object literal is passed each key-value pair will be registered on the module via $provide.value,
the key being the string name (or token) to associate with the value on the injector.
So it seems to me that the solution is using somehow angular.mock.module somehow to override the dependent
modules but so far I have not found a solution.
Any help much appreciated
By calling angular.module('AnotherModule1',[]) you are redefining the AnotherModule1, which I think is causing your downstream problems. Instead, use $provide for each dependent service. There's no need to mock the dependent modules.
Let's say your controller definition looks like this:
angular
.module('SaidModule', ['AnotherModule1', 'AnotherModule2'])
.controller('SaidController', [
'$scope',
'AnotherService',
function($scope, AnotherService) {
this.anotherService = AnotherService.helper();
}
);
Then your test might look like:
describe('SaidController', function() {
var controller, scope, AnotherService;
beforeEach(module('SaidModule'));
beforeEach(module(function($provide) {
AnotherService = { helper: function() { return 0; } };
$provide.value('AnotherService', AnotherService);
}));
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
controller = $controller('SaidController', {
$scope: scope
});
}));
it('creates controller', function() {
expect(controller).not.toBeNull();
});
});
There's no need to mock the dependent modules, just the dependent services.
I'm trying to make an Angular Service that houses common functions.
I bundled the code within my MVC app:
bundles.Add(new ScriptBundle("~/bundles/Angular")
.IncludeDirectory("~/app", "*.js", true));
And I checked in Developer Tools if it actually brought in my Common Folder with Common.js :
I added Common to the App :
var app = angular.module('app',
[
'JobCtrl',
'JobSvc',
'WebsiteCtrl',
'WebsiteSvc',
'myClientCtrl',
'ClientSvc',
'MediaCompanyCtrl',
'MediaCompanySvc',
'PageAlertSvc',
'ui.bootstrap',
'ui.bootstrap.tpls',
'Common'
]
);
and to the Controller:
angular.module('app', ['ui.bootstrap', 'ui.bootstrap.tpls'])
.controller('JobCtrl',
[
'JobService',
'WebsiteService',
'MediaCompanyService',
'ProductService',
'$scope',
'$uibModal',
'PageAlertService',
'Common',
function (JobService, WebsiteService, MediaCompanyService,
ProductService, $scope, $uibModal,PageAlertService, Common)
This is what my Common.js file looks like:
angular.module('app')
.service('Common', function () {
this.heyThere = function ()
{
console.log('Just wanted to say hey there')
};
});
Whenever it is called within my JobCtrl I get a Error: $injector:unpr
Unknown Provider.
Could anyone see what I may be doing wrong where it won't recognize my Common.js file? When I move Common.js to the Services folder and try calling it within my controller it works, but not when it is in my Common Folder. Makes no sense!
Thanks in advance!
That is simply because you are defining your app..twice!!!!
angular.module('app', []) // this is where you re-define your app
.service('Common', function () {
this.heyThere = function ()
{
console.log('Just wanted to say hey there')
};
});
should be:
angular.module('app')
.service('Common', function () {
this.heyThere = function ()
{
console.log('Just wanted to say hey there')
};
});
the module function has 2 modes.. with 2 arguments you are setting up your app.. with a single argument you just getting a reference to an existing app (which is already defined before that)
Please be careful when you use the declaration of a module. You are basically reassigning the app module to different instances.
angular.module('app', [dependencies]) //Constructs a module with dependencies
angular.module('app').service(...) //Associates the components (service)
//with the app module.
I am creating small application called puzometr. It is for educational needs only. I want to create this application using AngularJS. Also, I want to use RequireJS as module system.
I have strange problem. I created my test controller and I got problem: controller initialization fires two times.
Firstly, full code available here on GitHub (wait, don't click me, I will explain everything below).
So, problem is in myCtrl.js file. Here is code of this file:
define(['angular'], function (angular) {
var module = angular.module('main.myModule', []);
module.controller('main.myCtrl', function ($scope) {
console.log($scope.$id);
$scope.bob = function () {
}
})
});
It is included in main/controllers/controllers.js by this:
define(['app', 'main/controllers/myCtrl'], function (app) {
var module = angular.module('main.controllers', ['main.myModule']);
});
This file included in main.js by this code:
angular.module('main', ['ngRoute', 'main.services', 'main.controllers', 'main.directives']);
And main.js is included into app.js:
var app = angular.module('myApp', ['ngRoute', 'main', 'common']);
So, I incidentally noticed, that function definition in myCtrl controller fired two times. I put console.log there and saw this:
Can you please explain me why is this happens? Why controller is being initialised two times?
Also, I have this in ng-inspector:
So one scope is created as child for another scope. Notice, that scope with id 3 has correct controller name.
If you use ng-route to register controllers and bind them with views, then don't add them again using attributes in your html files.
I wrote a factory of Angular. There was a critical error for me. I wandered to fix it. Finally, I cleared this problem... without reason. So I need clear description of below code problem.
Here is my code A:
angular
.module('BinD', ['ngSails'])
.factory('UserService', function ($sails) {
...
});
And another B is:
(function (angular) {
'use strict';
angular
.module('BinD', ['ngSails'])
.factory('UserService', function ($sails) {
...
});
})(angular);
And the error part is:
(function (angular) {
'use strict';
angular
.module('BinD', ['ngSails'])
.controller('SignUpCtrl', function ($scope, $window, UserService) {
code B works well. code A made error message "UserServiceProvider is unknown(may?)". I really don't know why aforemetioned two same code works differently. Let me know about it.
Wrapping the .factory call in a function shouldn't make any difference. I think you must have made a different change as-well.
In your third code snippet, when you call .module with two parameters you create a new module. This would overwrite the module you created in either "Code A" or "Code B".
You are not reusing the same module, but creating a new one. Therefore it makes sense that your UserService does not exist on the new module.
Your last snippet should call .module('BinD') with only one parameter. Just the name of the module you want to use.
angular
.module('BinD')
.controller('SignUpCtrl', function ($scope, $window, UserService) {
Another option is that you only call .module once, and save it.
var app = angular.module('BinD', ['ngSails']);
Then later you can call app.controller or app.factory without having to worry about the syntax.
In your Code A or Code B in both part you had created one module BinD with the dependency of ngSails and then you are registering factory with that module, but Code A will declare a variable globally if you are using it & Code B will do the coding using IIFE pattern which will make your variable available inside the declared function only. But that doesn't related your error which you are getting.
Inside your controller you want utilize that factory, but while you are creating controller you shouldn't create a new module like by doing angular.module('BinD', ['ngSails']), which will flush the previously registered factory(or other components) with the BinD module and will create a new module with name BinD. That's why after injecting UserService inside your controller is throwing an $injector error, because the UserService is not available inside that module.
Controller
(function (angular) {
'use strict';
angular
.module('BinD') //<- utilizing already created module
.controller('SignUpCtrl', function ($scope, $window, UserService) {
I am a bit newbiew with javascript and i am starting to use angular.js
So my question is if there is a way to inject a controller inside a module that is declared in an anonymous function
my code looks like this
app.js
(function(angular) {
var app = angular.module('Organizer', ['ngMaterial', 'ngAnimate', 'ngAria']);
})(angular);
siteController.js
(function(angular, app) {
app.controller('site', function($scope, $mdDialog)
{
var alert = $mdDialog.alert({
title: 'Test',
content: 'Testing',
ok: 'Exit'
});
$mdDialog.show(alert);
});
})(angular);
i have tried to look for ways if it is possible, but still i would like to see if anyone here could explain how this can be made if it could.
Note: I have already used angular.js before and i wanted to try a different way to declare controllers so the client wont have any way to modify it
If you create a module in Angular, then you can not obfuscate it in this way. In the console, a user can just run angular.module('Organizer') to get access to your app, and then call any method they want on it.
The reason your code won't work as written, is because you are not passing the app variable to your anonymous function. So if you want to add a controller to the Organizer module, then you would do something like this:
(function(angular)
{
angular.
module('Organizer').
controller('site', function($scope, $mdDialog)
{
...
});
})(angular);
Theres no need to wrap any of this code in self executing functions as if you are trying to keep variables out of the global scope. The only one that's global is the "angular" object.
Your app.js should only have
'use strict';
angular.module('Organizer', ['ngMaterial', 'ngAnimate', 'ngAria']);
You controller file should only have
'use strict';
angular.module('Organizer').controller('siteController', function($scope, $mdDialog) {
var alert = $mdDialog.alert({
title: 'Test',
content: 'Testing',
ok: 'Exit'
});
$mdDialog.show(alert);
});
The first call to module in app.js passes the second parameter which angular uses to instantiate your module. Subsequent calls that omit the second parameter "get" the module.