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

后端 未结 7 1786
情深已故
情深已故 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:20

    Here is a simple, compact and easy to understand method I use.
    First, add a service in your js.

    app.factory('Helpers', [ function() {
          // Helper service body
    
            var o = {
            Helpers: []
    
            };
    
            // Dummy function with parameter being passed
            o.getFooBar = function(para) {
    
                var valueIneed = para + " " + "World!";
    
                return valueIneed;
    
              };
    
            // Other helper functions can be added here ...
    
            // And we return the helper object ...
            return o;
    
        }]);
    

    Then, in your controller, inject your helper object and use any available function with something like the following:

    app.controller('MainCtrl', [
    
    '$scope',
    'Helpers',
    
    function($scope, Helpers){
    
        $scope.sayIt = Helpers.getFooBar("Hello");
        console.log($scope.sayIt);
    
    }]);
    

提交回复
热议问题