Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 795
jbaiter Avatar asked Sep 16 '26 00:09

jbaiter


1 Answers

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

like image 64
mortalapeman Avatar answered Sep 18 '26 14:09

mortalapeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!