Custom Widget Binding

by Paul Lam

HTML

<div ng-app="app" ng-controller="myCtrl">
    <input type="text" ng-model="resource.name">
    <mycontrol bind-to="resource"></mycontrol>
</div>

JavaScript

angular.module('app', [])
  .directive('mycontrol', function($compile) {
    return {
      restrict:"E",
      scope: {
        bindTo: "=bindTo"
      },
      link: function(scope, iElem, iAttrs) {
        var html = '<div><input ng-model="' + '$parent.' + iAttrs.bindTo +'.name'+ '" /></div>';
        //alert(html);
        iElem.replaceWith($compile(html)(scope));
      }
    };
  })
  .controller('myCtrl', function($scope) {
    $scope.resource = {
      name: 'Paul'
    };
  });