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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12466661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 08:02:05  来源:igfitidea点击:

Using helper methods while templating with Angular JS

javascripttemplatesangularjsview-helpers

提问by yaegerbomb

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 methods to display data correctly. For instance:

目前正在将网站从以前的模板转换为 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>

This was very nice. Trying to figure out a way to utilize the same type of functionality with Angular as far as templating goes. Is it possible to do something similar? If so how?

这是非常好的。就模板而言,试图找出一种方法来利用与 Angular 相同类型的功能。有没有可能做类似的事情?如果是这样怎么办?

回答by Mark Rajcok

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":

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

<span class="posted-date">Posted {{CreatedDate | dateFormatter}}</span>

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.

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

过滤器的另一个好处是它们可以链接起来。因此,如果有一天您决定在应用程序中的某些地方空日期不应显示任何内容(空白),而在应用程序中的其他地方空日期应显示“TBD”,则过滤器可以解决后者:

<span class="posted-date">Posted {{CreatedDate | dateFormatter | tbdIfEmpty}}</span>

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

或者你的自定义过滤器可以接受一个或多个参数(上面的例子支持一个参数):

<span class="posted-date">Posted {{CreatedDate | dateFormatter:'TBD'}}</span>

回答by dnc253

You simply add the method to your controller. Something like this:

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

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

Then the controller:

然后控制器:

function MyCtrl($scope)
{
     $scope.parseDate = function(jsonDate) {
        //date parsing functionality
        return newParsedDate;
     }
}

回答by pkozlowski.opensource

Looking at the presented use case your best call would be the date filter described here: http://docs.angularjs.org/api/ng.filter:dateUsing this filter you could write:

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

{{CreatedDate | date}}

The mentioned filter is customizable so you could use different date formats etc.

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

Generally speaking filters are very nice for encapsulating formatting logic / UI helper functions. More on creating filters here: http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

一般来说,过滤器非常适合封装格式逻辑/UI 辅助函数。有关在此处创建过滤器的更多信息:http: //docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

Filters are nice and fit many use cases but if you are simply after using any function in your template it is possible. Just define a function in a scope and you are ready to use it directly in your template:

过滤器很好,适合许多用例,但如果您只是在模板中使用任何函数之后,这是可能的。只需在范围内定义一个函数,您就可以直接在模板中使用它:

{{doSomething(CreatedDate)}}

where doSomething needs to be defined on a scope (a current one or one of the parent scopes):

doSomething 需要在一个范围(当前的一个或父范围之一)上定义的地方:

function MyCtrl($scope) {

    $scope.doSomthing = function(argument){
        //ui helper logic here
    }    
}