Tuesday, 29 September 2015

angularjs where to put utility functions

1. root scope

2. service

3 general js:

One of the clear advantages here is that you can re-use them outside of your angular code and you can use them inside of your config function (which you can't do with services).
That being said, if you're looking for a generic way to re-use what should properly be services, the old answer I think is still a good one.
What I would do now is:
var MyNamespace = MyNamespace || {};

 MyNamespace.helpers = {
   isNotString: function(str) {
     return (typeof str !== "string");

 angular.module('app', ['app.controllers', 'app.services']).                             
   config(['$routeProvider', function($routeProvider) {
     // Routing stuff here...
angular.module('app.controllers', []).                                                                                                                                                                                  
  controller('firstCtrl', ['$scope', function($scope) {
    $scope.helpers = MyNamespace.helpers;
Then in your partial you can use:
<button data-ng-click="console.log(helpers.isNotString('this is a string'))">Log String Test</button>


No comments:

Post a comment