I have created angular service where I store my older non-angular javascript functions:
myApp.service('utils', function() {
return {
fun1: function(a, b, c, d) {
var x = a + b + c + d;
return x;
},
fun2: function() {
var x = fun1(1, 1, 1, 1);
return x;
}
};
});
If I call utils.fun2() in controller:
myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope', 'utils', function($scope, utils) {
$scope.someNumber = utils.fun2();
}]);
I get an error:
Error: fun1 is not defined
My question is, how to rewrite this that it will work (without polluting the global namespace)? What is the best approach for including existing Javascript functions to new angular app? Thank you.
Try to use factory and understand difference between factory and service.
Your code will work with these modifications:
angular.module('myModule', [])
.factory('utilsFactory', function() {
//function definition
var fun1 = function(a, b, c, d) {
var x = a + b + c + d;
return x;
};
//function definition
var fun2 = function() {
var x = fun1(1, 1, 1, 1);
return x;
};
//return functions after the injection
return {
fun1: fun1,
fun2: fun2
};
})
.controller('myController', ['$scope', 'utilsFactory', function($scope, utilsFactory) {
$scope.someNumber = utilsFactory.fun2();
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myModule' ng-controller='myController'>
someNumber = {{ someNumber }}
</div>
You have the right idea.
The problem is that with services you are injecting the exact function passed to the definition. So you need to call the injected function first to see those methods. You could change the service definition as follows too:
myApp.service('utils', function() {
this.fun1 = function(a, b, c, d) {
var x = a + b + c + d;
return x;
};
this.fun2 = function() {
var x = fun1(1, 1, 1, 1);
return x;
};
});
Also, you could change utils from 'service' to 'factory' and your code would work.
Read up on the differences between services and factories in the angular docs.
Try to set up your service like this:
myApp.service('utils', function() {
var fun1 = function(a, b, c, d) {
var x = a + b + c + d;
return x;
};
var fun2 = function() {
var x = fun1(1, 1, 1, 1);
return x;
};
return {
fun1: fun1,
fun2: fun2
};
});