I would like to add some utility functions to my AngularJS application. For example:
$scope.isNotString = function (str) {
return (typeof str !== \"strin
Coming on this old thread i wanted to stress that
1°) utility functions may (should?) be added to the rootscope via module.run. There is no need to instanciate a specific root level controller for this purpose.
angular.module('myApp').run(function($rootScope){
$rootScope.isNotString = function(str) {
return (typeof str !== "string");
}
});
2°) If you organize your code into separate modules you should use angular services or factory and then inject them into the function passed to the run block, as follow:
angular.module('myApp').factory('myHelperMethods', function(){
return {
isNotString: function(str) {
return (typeof str !== 'string');
}
}
});
angular.module('myApp').run(function($rootScope, myHelperMethods){
$rootScope.helpers = myHelperMethods;
});
3°) My understanding is that in views, for most of the cases you need these helper functions to apply some kind of formatting to strings you display. What you need in this last case is to use angular filters
And if you have structured some low level helper methods into angular services or factory, just inject them within your filter constructor :
angular.module('myApp').filter('myFilter', function(myHelperMethods){
return function(aString){
if (myHelperMethods.isNotString(aString)){
return
}
else{
// something else
}
}
);
And in your view :
{{ aString | myFilter }}