title: Binding data in a custom directive - AngularJS
body: <p>I have a custom directive, and its purpose is to present a widget and bind it to a variable.
  Every variable has different data type, so different widgets will be presented depending on the data type.</p>
  
  <p>My problem is that I can pass the data of the variable, but I can't manage to bind the widget to it.</p>
  
  <p>To simplify the problem, my widget is just a simple text input.
  When I try to $compile the widget, Angular uses the value of the variable instead of binding to it.</p>
  
  <p>HTML:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;body ng-app="app" ng-controller="myCtrl"&gt;
    &lt;input type="text" ng-model="resource.name"&gt;&lt;/div&gt;
    &lt;div custom-widget widget-type="widget" bind-to="resource"&gt;&lt;/div&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>Javascript:</p>
  
  <pre class="lang-js prettyprint-override"><code>angular.module('app', [])
    .directive('customWidget', function($compile) {
      return {
        replace: true,
        template: '&lt;div&gt;&lt;/div&gt;',
        controller: function($scope) {
  
        },
        scope: {
          bindTo: "=bindTo",
          widgetType: "=widgetType"
        },
        link: function(scope, iElem, iAttrs) {
          var html = '&lt;div&gt;' + scope.widgetType.label + ':&lt;input ng-bind="' + scope.bindTo[scope.widgetType.id] + '" /&gt;&lt;/div&gt;';
          iElem.replaceWith($compile(html)(scope));
        }
      };
    })
    .controller('myCtrl', function($scope) {
      $scope.widget = {
        id: 'name',
        label: 'Text input',
        type: 'text'
      };
      $scope.resource = {
        name: 'John'
      };
    });
  </code></pre>
  
  <p>Plunker demo: <a href="http://plnkr.co/edit/qhUdNhjSN7NlP4xRVcEA?p=preview" rel="nofollow">http://plnkr.co/edit/qhUdNhjSN7NlP4xRVcEA?p=preview</a></p>
  
  <p>I'm still new to AngularJS and my approach may not be the best, so any different ideas are of course appreciated!</p>