2

I have a fairly simple UI control that I've modeled as a directive, which is an editor for phone numbers that has two input fields: one for the country code and another for the number.

The directive's usage looks like this:

<phone-editor ng-model='phoneNo'></phone-editor>

In the directive's declaration, I require ngModel and the template looks like this:

<input type="text" ng-model="countryCode" />
<input type="text" ng-model="number" />

It's clear how to compose and decompose the original model into the two fields.

What I cannot figure out is - how do I use a formatter for the second field such that it displays (555) 555-5555 instead of the plain number, without defining another directive just to access the ngModel controller of the second input field?

Can I somehow access the child ngModel controller?

georgiosd
  • 3,038
  • 3
  • 39
  • 51
  • 1
    I don't think I'd nest ng-models, rather I would deal with the inputs directly, since I'm already in a directive and that's the place to do DOM manipulation. – Ben Lesh Mar 08 '13 at 19:39

1 Answers1

4

I did a few searches on the Angular codebase and found something that should work:

app.directive('phoneEditor', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div>'
      + '<input type="text" ng-model="countryCode">'
      + '<input type="text" ng-model="number">'
      + '</div>',
    link: function(scope, element) {
      scope.number = 555;
      var input1 = element.find('input').eq(0);
      var input2 = element.find('input').eq(1);
      input1Ctrl = input1.controller('ngModel');
      input2Ctrl = input2.controller('ngModel');
      console.log(input1Ctrl, input2Ctrl);
    }
  };
});

Plunker.

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492