Yarin Yarin - 6 months ago 30
Javascript Question

Using Angular formatters / parsers

Can't seem to get Angular formatters and parsers working:

app.js:

var itemApp = angular.module('itemApp', []);

itemApp.controller('ItemController', ['$scope', function($scope) {

$scope.some_value = 'abcEFG';

}]);

itemApp.directive('changeCase', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {

ngModel.$formatters.push(function(value){
return value.toUpperCase();
});

ngModel.$parsers.push(function(value){
return value.toLowerCase();
});

}
};
});


view.html:

<input ng-model="some_value" changeCase>


It doesn't work- no errors, just nothing happens to the values in the input or the model. I'm newish to Angular, having trouble figuring out how I'd even debug this.

Answer

Try to write:

<input ng-model="some_value" change-case> //camel-case

This is explained in angular docs

Normalization

Angular normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).

The normalization process is as follows:

  • Strip x- and data- from the front of the element/attributes.
  • Convert or _-delimited name to camelCase.