如何从浏览器控制台访问和测试 AngularJS 过滤器? [英] How can I access and test an AngularJS filter from the browser console?

查看:27
本文介绍了如何从浏览器控制台访问和测试 AngularJS 过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个测试过滤器,比如这个 'capitalize' 过滤器这将使每个单词的第一个字母大写:

Given a test filter, say this 'capitalize' filter that will capitalize the first letter of each word:

return function (input) {
  return (!!input) ? input.replace(/([^\W_]+[^\s-]*) */g, function (txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  }) : '';
}

如何从浏览器的 JavaScript 控制台测试此过滤器?

How can this filter be tested from a browser's JavaScript console?

推荐答案

过滤器可以在 HTML 模板绑定中调用 {{myString |大写}},但要在浏览器中访问它,我们有一个很好的选择.考虑一下:

Filters can be called in HTML template binding {{myString | capitalize}}, but to gain access to it in the browser we have an excellent option. Consider this:

$filter('filter')(array, expression,comparator) 每个 Angular $filter 文档

实现一个过滤器可以通过$filter服务调用,这样你就可以这样访问、调用和测试capitalize过滤器:

Realizing a filter can be called via the$filter service, you can thus access, call and test the capitalize filter this way:

angular.element(document.body).injector().get('$filter')('capitalize')('capitalization test')

控制台中的结果?大小写测试"

具有多个输入的过滤器怎么样?只需添加参数,例如,如果 capitalize 过滤器有第二个布尔参数以将大写限制为仅第一个单词:

What about a filter with more than one input? Just add the parameter, for instance if the capitalize filter had a second boolean parameter to restrict capitalization to the first word only:

angular.element(document.body).injector().get('$filter')('capitalize')('capitalization test', true)

angular.element(document.body).injector().get('$filter')('capitalize').apply(null, ['capitalization test', true])

感谢这篇关于从控制台访问服务的文章和相关博客条目:从控制台访问服务.

Kudos to this SO article and related blog entries for posting on accessing services from the console: access service from console.

这篇关于如何从浏览器控制台访问和测试 AngularJS 过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆