Skip to content Skip to sidebar Skip to footer

AngularJS Creating A Directive Then Uses Another Directive

I'm trying to create a directive to cut down on the boilerplate code that I'd have to write. I'm using the angular xeditable directive to allow for inline editing, but when I add t

Solution 1:

You have to recompile the element after adding those attributes, here is an example:

Example plunker: http://plnkr.co/edit/00Lb4A9rVSZuZjkNyn2o?p=preview

.directive('edit', function($compile) {
  return {
    restrict: 'A',
    priority: 1000,
    terminal: true, // only compile this directive at first, will compile others later in link function
    template: function (tElement, tAttrs) {
      return '{{ content.' + tAttrs.edit + '.data }}';
    },
    link: function(scope, element, attrs) {
      attrs.$set('editable-text', 'content.' + attrs.edit + '.data');
      attrs.$set('onbeforesave', 'update($data, content.' + attrs.edit + '.id)');
      attrs.$set('edit', null); // remove self to avoid recursion.
      $compile(element)(scope);
    }
  }
});

Things to consider:

  • remove the isolated scope to simplify things as it seems you would like to do the binding directly to a scope in controller content.portrait_description_title.data in the first place.
  • template: also accept function, this way you can get the edit attribute value to construct the template.
  • mark as a terminal directive and raise priority, so that at first run, only this diective (out of others in the same element) will get compiled.
  • attrs.$set() is useful for adding/removing attributes, use it to add the editable-text directive and onbeforesave.
  • remove the directive itself, i.e. the edit attribute, to prevent a recursion after a next compilation.
  • use $compile service to recompile the element, in order to make editable-text and onbeforesave works.

Hope this helps.


Solution 2:

Just add another directive inside template of first directive and bind it to scope model that you get from attr. You can also add controller function, and create more models, or logic and bind to directive template.

Also maybe your attributes may not be available on template, than you need to add $watch to your isolated scope model and update another scope model inside controller. That second one model needs to be binded to template. More information about directives you can find on AngularJS docs, but also here is one good article, it can help you:

http://www.sitepoint.com/practical-guide-angularjs-directives-part-two/


Post a Comment for "AngularJS Creating A Directive Then Uses Another Directive"