I would like to add some utility functions to my AngularJS application. For example:
$scope.isNotString = function (str) {
return (typeof str !== "string");
}
Is the best way to do this to add them as a service? From what I have read I can do this but then I would like to use these in my HTML pages so is it still possible if they are in a service? For example can I use the following:
<button data-ng-click="doSomething()"
data-ng-disabled="isNotString(abc)">Do Something
</button>
Can someone give me an example of how I could add these. Should I create a service or is there some other way of doing it. Most important I would like these utility functions in a file and not combined with another part of the main set up.
I understand there's a few solutions but none of them are so clear.
Solution 1 - Proposed by Urban
$scope.doSomething = ServiceName.functionName;
The problem here is I have 20 functions and ten controllers. If I did this it would mean adding a lot of code to each controller.
Solution 2 - Proposed by me
var factory = {
Setup: function ($scope) {
$scope.isNotString = function (str) {
return (typeof str !== "string");
}
The disadvantage of this is that at the start of every controller I would have one or more of these Setup calls to each service which passed the $scope.
Solution 3 - Proposed by Urban
The solution proposed by urban of creating a generic service looks good. Here's my main set up:
var app = angular
.module('app', ['ngAnimate', 'ui.router', 'admin', 'home', 'questions', 'ngResource', 'LocalStorageModule'])
.config(['$locationProvider', '$sceProvider', '$stateProvider',
function ($locationProvider, $sceProvider, $stateProvider) {
$sceProvider.enabled(false);
$locationProvider.html5Mode(true);
Should I add the generic service to this and how could I do it ?