Customizing the template within a Directive

前端 未结 4 1538
醉话见心
醉话见心 2020-11-28 00:25

I have a form that is using markup from Bootstrap, like the following:

Legend tex
4条回答
  •  情话喂你
    2020-11-28 01:04

    The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:

    
    
      
    
    
    // directive
    angular.module('app')
    .directive('formField', function($compile, $parse) {
      return { 
        restrict: 'E', 
        compile: function(element, attrs) {
          var fieldGetter = $parse(attrs.field);
    
          return function (scope, element, attrs) {
            var template, field, id;
            field = fieldGetter(scope);
            template = '..your dom structure here...'
            element.replaceWith($compile(template)(scope));
          }
        }
      }
    })
    

    I've created a gist with more complete code and a writeup of the approach.

提交回复
热议问题