Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 239
ryanm Avatar asked May 23 '16 19:05

ryanm


People also ask

How do you access $scope in console?

To examine the scope in the debugger: Right click on the element of interest in your browser and select 'inspect element'. You should see the browser debugger with the element you clicked on highlighted. The debugger allows you to access the currently selected element in the console as $0 variable.

How do I view angular variables in browser console?

You could use the following in the console: angular. element(document. querySelector('[ng-controller=hw]')).

What is the correct way to apply filter in AngularJS?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for the filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.

How does filter work in AngularJS?

The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.


1 Answers

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.

like image 169
ryanm Avatar answered Oct 29 '22 19:10

ryanm