Using helper methods while templating with Angular JS

后端 未结 3 605
粉色の甜心
粉色の甜心 2020-12-15 19:57

Currently in the process of converting a website from its previous templating to Angular. In the previous templating process we were using we were able to call helper method

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 20:24

    If you are only interested in data display, then as pkozlowski.opensource already mentioned, filters are the "Angular way" of formatting data for display. If the existing date filter is not sufficient, I suggest a custom filter. Then your HTML will look more "angular":

    Posted {{CreatedDate | dateFormatter}}
    

    The above syntax makes it clear that you're (only) formatting.

    Here's a custom filter:

    angular.module('OurFormatters', []).
     filter('dateFormatter', function() {               // filter is a factory function
       return function(unformattedDate, emptyStrText) { // first arg is the input, rest are filter params
           // ... add date parsing and formatting code here ...
           if(formattedDate === "" && emptyStrText) {
                formattedDate = emptyStrText;
           }
           return formattedDate;
       }
     });
    

    By encapsulating our filters/formatters into a module, it is also easier to (re)use them in multiple controllers -- each controller that needs them just injects OurFormatters.

    Another benefit of filters is that they can be chained. So if someday you decide that in some places in your app empty dates should show nothing (be blank), whereas in other places in your app empty dates should show 'TBD', a filter could solve the latter:

    Posted {{CreatedDate | dateFormatter | tbdIfEmpty}}
    

    Or your custom filter can take one or more arguments (the above example supports an argument):

    Posted {{CreatedDate | dateFormatter:'TBD'}}
    

提交回复
热议问题