Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a directive with a variable element type

I'm trying to create a directive that will change the html element type (h1/h2/h3) by using a drop down selector of "Large", "Medium", "Small". I want it to also retain attributes on the element. I have created a fiddle of this example: http://jsfiddle.net/H63Z3/1/

Angular:

angular.module('app', [])
        .controller('example', function ($scope) {
            $scope.type = 'h2';
        })
        .directive('changeType', function ($compile) {
            return {
                restrict: 'A',
                link: function (scope, element, attributes) {
                    scope.$watch('type', function () {
                        var attrs = element[0].attributes;
                        var newElement = $('<' + scope.type + '>').text(element.text());
                        for (var i = 0; i < attrs.length; i++) {
                            newElement.attr(attrs.item(i).name, attrs.item(i).value);
                        }
                        element.replaceWith(newElement);
                        $compile(element.contents())(scope);
                    });
                }
            };
        });

HTM & L:

<div ng-app="app" ng-controller="example">
    <select ng-model="type" ng-options="k as v for (k,v) in { h1: 'Large', h2: 'Medium', h3: 'Small' }"></select>
    <h1 change-type>Text</h1>

    <div>{{ type }}</div>
</div>

The problem I see is that the element property is not being updated properly in Angular after a change is made by the drop down. It seems that the directive is not reapplied to the new element. I'm unsure if using a compile function is the right answer.

Any help would be greatly appreciated.

like image 862
farleyrw Avatar asked Jul 23 '14 20:07

farleyrw


1 Answers

I just spent a little while working on what I decided to call a 'morphling' directive. It was pretty fun actually, and I'm quite pleased with the result. Note that this solution is pure Angular.

Note: I failed to notice when I first posted this that you required persistent attributes. I have since added that functionality. I add my attributes after compilation, but if you want to supply directives as attributes, you'd have to do it the other way around.

HTML

<h1>AngularJS 'Morphling' Directive</h1>
<div ng-app="app" ng-controller="morphTest">
  <strong>Morphling directive type:</strong> <select ng-model="type" ng-options="tag as caption for (tag, caption) in { h1: 'Heading 1', h2: 'Heading 2', h3: 'Heading 3', li: 'List Item', quote: 'Quote', attrDemo: 'Attribute Persistence Demo' }"></select><br />
  <morphling type="type" attr="value">Normal <span style="color: red">{{bindingDemo}}</span> Works</morphling>
</div>

LESS

html, body {
  font-family: sans-serif;
  color: #111;
}

quote {
  display: block;
  margin: 20px;
  font-style: italic;
  &:before,
  &:after {
    content: '"';
  }
}

attrDemo[attr="value"] {
  display: inline-block;
  color: blue;
  -webkit-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  transform: rotate(180deg);
}

Javascript

angular.module('app', [])
  .controller('morphTest', function ($scope) {
    $scope.type = 'h2';
    $scope.bindingDemo = 'Binding';
  })
  .directive('morphling', function ($compile) {
    return {
      restrict: 'E',
      replace: true,
      link: function(scope, element, attributes) {
        var e = element;
        scope.$watch(attributes.type, function(type){
          type = !!type ? type : 'span';
          var e2 = $compile('<' + type + '>' + e.html() + '</' + type + '>')(scope);
          for(var a in attributes.$attr) {
            if(a.toLowerCase() != 'type')
              e2.attr(a, attributes[a]);
          }
          e.replaceWith(e2);
          e = e2;
        });
      }
    };
  });

Demo

CodePen Demo

like image 183
mirichan Avatar answered Sep 16 '22 13:09

mirichan