问题描述
给出一个测试过滤器,说出大写"过滤器将大写每个单词的第一个字母:
return function (input) {
return (!!input) ? input.replace(/([^\W_]+[^\s-]*) */g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}) : '';
}
如何从浏览器的JavaScript控制台测试此过滤器?
可以在HTML模板绑定{{myString |大写}},但是要在浏览器中访问它,我们有一个不错的选择.考虑一下:
$filter('filter')(array, expression, comparator)
每个角度$ filter文档
可以通过$filter
服务调用实现过滤器,因此您可以通过以下方式访问,调用和测试capitalize
过滤器:
angular.element(document.body).injector().get('$filter')('capitalize')('capitalization test')
控制台中的结果? "Capitalization Test"
具有多个输入的过滤器怎么样?只需添加参数,例如,如果capitalize
过滤器具有第二个布尔参数以将大写字母限制为仅第一个单词,则将其大写:
angular.element(document.body).injector().get('$filter')('capitalize')('capitalization test', true)
OR
angular.element(document.body).injector().get('$filter')('capitalize').apply(null, ['capitalization test', true])
对于此SO文章和相关博客条目的荣誉,以便从控制台发布有关访问服务的信息:.
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();
}) : '';
}
How can this filter be tested from a browser's JavaScript console?
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)
per Angular $filter documentation
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')
The result in the console? "Capitalization Test"
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)
OR
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过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!