Search code examples
angularjsangularjs-compile

Angularjs dynamic html string compilation with an directive included inside


I have been trying a dynamic html string parsing with recursive directives which works but two-way binding doesn't seems to be working.Need a little help here.Below is the plunker: http://plnkr.co/edit/ovz2RJDmnHPgLUqUaH7M Here is the Code:

 var model = angular.module('modelApp', ['ui.bootstrap']);

model.controller('modalCtrl', ['$scope', '$window',
  function($scope, $window) {
    var modalctrl = this;
    modalctrl.form = {};

    $scope.showMeModalValues = function(){
      console.log(modalctrl.form);
    };
  }
]);

model.directive('contentInput', ['$compile',
  function($compile) {
    return {
      require: '^ngController',
      restrict: 'EA',
      link: function(scope, element, attrs, ctrl) {
        element.html('<input type="text" ng-model="ctrl.form.' + attrs.name + '" />');
        $compile(element.contents())(scope);
      }
    };
  }
]);

model.directive('dynamicInput', ['$compile', '$sce',
  function($compile, $sce) {
    return {
      templateUrl: 'myContent.html',
      require: '^ngController',
      restrict: 'EA',
      link: function(scope, element, attrs, ctrl) {
        var html = '<content-input name=' + attrs.name + '></content-input>';
        scope.html = $sce.trustAsHtml(html);
      }
    };
  }
]);

model.directive('reCompile', ['$compile',
  function($compile){
    return {
      require: '^ngController',
      restrict: 'EA',
      link: function(scope, element, attrs, ctrl){
        scope.$watch(attrs.reCompile , function(value){
          element.html(value);
          $compile(element.contents())(scope);
        });
      }
    };
  }]);

Solution

  • I have figured out the problem!! Assiging scope.ctrl with ctrl resolves the issue of not updating modalctrl.form Plunker with working solution: http://plnkr.co/edit/ovz2RJDmnHPgLUqUaH7M

    model.directive('dynamicInput', ['$compile', '$sce',
      function($compile, $sce) {
        return {
          templateUrl: 'myContent.html',
          require: '^ngController',
          restrict: 'EA',
          link: function(scope, element, attrs, ctrl) {
            scope.ctrl = ctrl;
            var html = '<content-input name=' + attrs.name + '></content-input>';
            scope.html = $sce.trustAsHtml(html);
          }
        };
      }
    ]);