title: AngularJS - Create a directive that uses ng-model
body: <p>I am trying to create a directive that would create an input field with the same ng-model as the element that creates the directive.</p>
  
  <p>Here's what I came up with so far:</p>
  
  <p><strong>HTML</strong></p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;!doctype html&gt;
  &lt;html ng-app="plunker" &gt;
  &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;AngularJS Plunker&lt;/title&gt;
    &lt;link rel="stylesheet" href="style.css"&gt;
    &lt;script&gt;document.write("&lt;base href=\"" + document.location + "\" /&gt;");&lt;/script&gt;
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt;
    &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"&gt;&lt;/script&gt;
    &lt;script src="app.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body ng-controller="MainCtrl"&gt;
    This scope value &lt;input ng-model="name"&gt;
    &lt;my-directive ng-model="name"&gt;&lt;/my-directive&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>JavaScript</strong></p>
  
  <pre class="lang-js prettyprint-override"><code>var app = angular.module('plunker', []);
  
  app.controller('MainCtrl', function($scope) {
    $scope.name = "Felipe";
  });
  
  app.directive('myDirective', function($compile) {
    return {
      restrict: 'E',
      scope: {
        ngModel: '='
      },
      template: '&lt;div class="some"&gt;&lt;label for="{{id}}"&gt;{{label}}&lt;/label&gt;' +
        '&lt;input id="{{id}}" ng-model="value"&gt;&lt;/div&gt;',
      replace: true,
      require: 'ngModel',
      link: function($scope, elem, attr, ctrl) {
        $scope.label = attr.ngModel;
        $scope.id = attr.ngModel;
        console.debug(attr.ngModel);
        console.debug($scope.$parent.$eval(attr.ngModel));
        var textField = $('input', elem).
          attr('ng-model', attr.ngModel).
          val($scope.$parent.$eval(attr.ngModel));
  
        $compile(textField)($scope.$parent);
      }
    };
  });
  </code></pre>
  
  <p>However, I am not confident this is the right way to handle this scenario, and there is a bug that my control is not getting initialized with the value of the ng-model target field.</p>
  
  <p>Here's a Plunker of the code above: <a href="http://plnkr.co/edit/IvrDbJ" rel="noreferrer">http://plnkr.co/edit/IvrDbJ</a></p>
  
  <p>What's the correct way of handling this?</p>
  
  <p><strong>EDIT</strong>: After removing the <code>ng-model="value"</code> from the template, this seems to be working fine. However, I will keep this question open because I want to double check this is the right way of doing this.</p>