How can I access and test an AngularJS filter from the browser console?

纵饮孤独 提交于 2019-11-30 05:28:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/37399331/how-can-i-access-and-test-an-angularjs-filter-from-the-browser-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!