I have a situation where I've downloaded a written service for angular.js
, and it works fine - but I would prefer to have it called something different in my code just for the convenience and readability. It isn't really a requirement, just a desire.
I could go through and change this in the actual source code for the service, but that's obviously going to lead to all kinds of problems. So I was wondering, is this kind of thing possible? Can you 'alias' a service across your application so that it can be referred to something differently when you're passing it through controllers? For example...
var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);
app.controller('HomeController', function(ngSomethingLongAndObtuseThatIsNotNecessary){
ngSomethingLongAndObtuseThatIsNotNecessary.open();
});
var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);
var smallerName = ngSomethingLongAndObtuseThatIsNotNecessary;
app.controller('HomeController', function(smallerName){
smallerName.open();
});
I tried just doing that, assigning it to another variable, but it didn't work.
I actually did make something work, but I'm not sure if this will have bad repercussions down the line.
var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);
app.service('ngSmaller', function(ngSomethingLongAndObtuseThatIsNotNecessary) {
return ngSomethingLongAndObtuseThatIsNotNecessary;
});
app.controller('HomeController', function(ngSmaller){
ngSmaller.open();
});
You can inject it like that, this way the services names as strings in array will be resolved to the name of attributes in function, ORDER is important
app.controller('HomeController', ['ngSomethingLongAndObtuseThatIsNotNecessary', function(shortName){
shortName.open();
}]);
---edit -----
or with injector
var injector = angular.injector(['demo', 'ng']);
var shortName = injector.get('ngSomethingLongAndObtuseThatIsNotNecessary');
app.controller('HomeController', function(shortName){
shortName.open();
});
You can redefine the service with an alias name and then use it everywhere in the application. It will even keep the same one instance even if you use the long name:
app.service("shortName", ["ngSomethingLongAndObtuseThatIsNotNecessary", function (originalService) { return originalService; }]);
app.controller("HomeController", ["shortName", function(service) {
service.open();
}]);
Similarly you can alias whole modules:
angular.module("shortModuleName", ["veryVeryLoooooooooooooooooooongModuleName"]);
Another approach can be just create a new factory with a smaller name but use functionality of the existing service. Possibly can help in achieving what you want without polluting the global namespace.
angular.module('myApp').factory('simpleService',['IHaveAVeryLongOrConfusingName', function(foo){
return foo;
}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With