1

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.

Yarin
  • 173,523
  • 149
  • 402
  • 512
  • 1
    [toUpperCase](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) and [toLowerCase](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) and all string manipulating methods do not manipulate the string in place, they return the transformed string. So you would do `return value.toUpperCase()` etc – Patrick Evans Jun 10 '16 at 20:53
  • Sorry, sloppy example code. Still doesn't work though – Yarin Jun 10 '16 at 21:22

1 Answers1

1

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.
Yarin
  • 173,523
  • 149
  • 402
  • 512
Lucas
  • 1,251
  • 4
  • 16
  • 34