How can I add some small utility functions to my AngularJS application?

后端 未结 7 1781
情深已故
情深已故 2020-12-02 03:46

I would like to add some utility functions to my AngularJS application. For example:

$scope.isNotString = function (str) {
    return (typeof str !== \"strin         


        
7条回答
  •  长情又很酷
    2020-12-02 04:30

    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 }}   
    

提交回复
热议问题