使用Angular JS进行模板化时使用辅助方法

yae*_*omb 19 javascript templates view-helpers angularjs

目前正在将网站从之前的模板转换为Angular.在我们之前使用的模板化过程中,我们能够调用辅助方法来正确显示数据.例如:

<script type="text/javascript">
$.views.helpers({
    parseDate: function (jsonDate) {
      if (jsonDate != null) {
        var newDate = Utils.PrettyDate(Utils.ConvertJsonDateToJsDate(jsonDate));
        return newDate;
      }
    }
});
</script>


<div class="post-info">
  <span class="posted-date">Posted {{ :~parseDate(CreatedDate) }}</span>
  &nbsp|&nbsp
  <span>{{ :ReplyCount }} Replies</span>
</div>
Run Code Online (Sandbox Code Playgroud)

这非常好.试图找出一种方法来使用与Angular相同类型的功能进行模板化.有可能做类似的事情吗?如果是这样的话?

Mar*_*cok 34

如果您只对数据显示感兴趣,那么就像pkozlowski.opensource已经提到的那样,过滤器是格式化显示数据的"Angular方式".如果现有的日期过滤器不够用,我建议使用自定义过滤器.然后你的HTML看起来会更"有棱角":

<span class="posted-date">Posted {{CreatedDate | dateFormatter}}</span>
Run Code Online (Sandbox Code Playgroud)

上面的语法清楚地表明您(仅)格式化.

这是一个自定义过滤器:

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;
   }
 });
Run Code Online (Sandbox Code Playgroud)

通过将我们的过滤器/格式化程序封装到一个模块中,它也更容易(重新)在多个控制器中使用它们 - 每个需要它们的控制器只注入OurFormatters.

过滤器的另一个好处是它们可以链接.因此,如果有一天你决定在你的应用程序的某些地方空白日期应该什么都不显示(空白),而在你的应用程序的其他地方空白日期应该显示'TBD',过滤器可以解决后者:

<span class="posted-date">Posted {{CreatedDate | dateFormatter | tbdIfEmpty}}</span>
Run Code Online (Sandbox Code Playgroud)

或者您的自定义过滤器可以使用一个或多个参数(上面的示例支持参数):

<span class="posted-date">Posted {{CreatedDate | dateFormatter:'TBD'}}</span>
Run Code Online (Sandbox Code Playgroud)


dnc*_*253 32

您只需将方法添加到控制器.像这样的东西:

<div class="post-info" ng-controller="MyCtrl">
    <span class="posted-date">Posted {{parseDate(CreatedDate)}}</span>
</div>
Run Code Online (Sandbox Code Playgroud)

然后控制器:

function MyCtrl($scope)
{
     $scope.parseDate = function(jsonDate) {
        //date parsing functionality
        return newParsedDate;
     }
}
Run Code Online (Sandbox Code Playgroud)


pko*_*rce 7

查看提供的用例,您最好的调用是此处描述的日期过滤器:http://docs.angularjs.org/api/ng.filter:date 使用此过滤器,您可以编写:

{{CreatedDate | date}}
Run Code Online (Sandbox Code Playgroud)

提到的过滤器是可定制的,因此您可以使用不同的日期格式等.

一般而言,过滤器非常适合封装格式化逻辑/ UI辅助函数.有关创建过滤器的更多信息,请访问:http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

过滤器非常好,适合许多用例,但如果您只是在模板中使用任何功能后就可以使用.只需在作用域中定义一个函数,您就可以直接在模板中使用它:

{{doSomething(CreatedDate)}}
Run Code Online (Sandbox Code Playgroud)

doSomething需要在作用域(当前的一个或一个父作用域)上定义:

function MyCtrl($scope) {

    $scope.doSomthing = function(argument){
        //ui helper logic here
    }    
}
Run Code Online (Sandbox Code Playgroud)