Yarin
Yarin

Reputation: 183419

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.

Upvotes: 1

Views: 138

Answers (1)

Lucas
Lucas

Reputation: 1271

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.

Upvotes: 1

Related Questions