jbaiter
jbaiter

Reputation: 7099

AngularJS: Link element to controller in directive

I have a custom directive <my-configform></my-configform> in which I get a JSON array from an API during the compile stage and dynamically construct the element's DOM from:

angular.module('mymodule').directive('myConfigform', function($http, $compile, $interpolate) {
  restrict: 'E',
  controller: 'ConfigCtrl', // Added as per Craig's suggestion
  compile: function(element) {
    var buildMyForm = function(data) {
      var template = $interpolate('<form role="form">{{form}}</form>');
      var formMarkup;
      // ... build formMarkup from data ...
      // just as a very simple example what it could look like:
      formMarkup = '<input type="checkbox" ng-model="config.ticked"> Tick me';

      return template({form: formMarkup});
    };
    $http.get('/api/some/endpoint').success(function(data) {
      element.replaceWith(buildMyForm());
    });
  }
});

My problem is that the form is not bound to the controller after compilation. The elements are all in the DOM, but the ConfigCtrl controller is not created and no data binding has taken place. How can I tell Angular to bind the controller to my dynamically created form?

Upvotes: 3

Views: 2781

Answers (1)

mortalapeman
mortalapeman

Reputation: 1425

You need to compile the generated html inside the post linking function like below:

.directive('myConfigform', function($http, $compile, $interpolate) {
    return {
      restrict: 'E',
      compile: function(element) {
        var buildMyForm = function(data) {
          var template = $interpolate('<form role="form">{{form}}</form>');
          var formMarkup = '<input type="checkbox" ng-model="config.ticked"> Tick me';
          return template({form: formMarkup});
        };
        element.replaceWith(buildMyForm());
        return function(scope, element) {
          $compile(element.contents())(scope);
        };
      }
    };
  });

Here is a working plunker

Upvotes: 4

Related Questions