Arti Arti - 1 year ago 44
AngularJS Question

Good practice to use global objects in angular

I'm creating desktop app using nw.js framework with angular. In my controllers, services etc. i often use

Node.js
modules like this:

module.exports = function(ngModule) {
ngModule.service('User', ['$q', function ($q) {
var self = this;
var fs = require('fs');
var path = require('path');
var gui = require('nw.gui');
}]);
};


Is this a good practice ? Or maybe better create some service or put modules in $
rootScope
?

Answer Source

Generally requires should not remain within service constructor (unless they are conditional):

var fs = require('fs');
var path = require('path');
var gui = require('nw.gui');

ngModule.service('User', ['$q', function ($q) {
  ...
}]);

The code above will require to use packages like proxyquire to mock Node modules and test the service in isolation.

DI is supposed to introduce additional flexibility and testability to the application. Having the dependencies in separate module that can be easily stubbed is generally preferable way to handle this:

angular.module('node', [])
.constant('gui', require('nw.gui'))
...

...

angular.module('app', ['node'])
.service('User', function ($q, gui, ...) {
  ...
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download