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:
app.js:
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...
   }]);
controller.js:
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>




http://stackoverflow.com/questions/19614545/how-can-i-add-some-small-utility-functions-to-my-angularjs-application




No comments:

Post a comment