pQuestions123
pQuestions123

Reputation: 4611

directive tries to access ngModel value - not coming through correctly

Here is the directive:

(function () {
    'use strict';

    angular
        .module('utils')
        .directive('phoneNumberInputFormat', phoneNumberInputFormat);

    phoneNumberInputFormat.$inject = ['$filter'];

    function phoneNumberInputFormat($filter) {
        return {
            link: link,
            scope: {
                model: '=ngModel'
            },
            restrict: 'A'
        };

        function link(scope, element, attributes) {

            scope.$watch('model', function (value, oldValue) {
                var number = String(value).replace(/[^0-9]+/g, '');
                scope.model = $filter('phoneNumber')(number);
            });
        }
    }

})();

I am trying to basically modify the value in a textbox to look like a standard telephone number. I use this directive as an attribute on a textbox. The problem is that the scope.model is either "" or undefined all the time. I expect it to point to the property that the textbox is modeling so that, as the value changes , this directive is formatting the telephone number correctly.

html:

<input phone-number-input-format name="phone" 
  ng-minlength="14" 
  ng-maxlength="14" 
  ng-change="vm.phoneOrEmail()" 
  class="form-control form-group-lg" 
  placeholder="Phone Number" 
  type="tel" 
  ng-model="vm.registrant.HOME_PHONE_NR">

Upvotes: 1

Views: 38

Answers (1)

Ori Price
Ori Price

Reputation: 4221

Your code is just fine. The reason you don't see model changes is because you limited your input to exactly 14 characters. This means angular will change your model only when the limitations are met, AKA: 14 characters. if you'll set ng-minlength="1" you'll see your changes on each typed characters. See: Working Example

Upvotes: 1

Related Questions