Creating a directive with a variable element type

廉价感情. 提交于 2019-12-10 14:04:28

问题


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.


回答1:


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




回答2:


@Michael Mroz

I would like to point out that the solution you proposed breaks the binding: http://codepen.io/anon/pen/PwLzQX

angular.module('app', [])
  .controller('morphTest', function ($scope, $interval) {
    $scope.type = 'h2';
    $scope.bindingDemo = 'Binding';

    var i = 0;
    $interval(function() {
      $scope.bindingDemo = 'Binding ' + ++i;
    }, 1000);
  })
  .directive('morphling', function ($compile) {
    return {
      restrict: 'E',
      replace: true,
      link: function(scope, element, attributes) {
        // return; // uncomment here

        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;
        });
      }
    };
  });

You should see "Normal Binding [number] Works" with [number] incrementing, but it's not showing.

Uncomment the return; in the link function and you will see the binding working.



来源:https://stackoverflow.com/questions/24920456/creating-a-directive-with-a-variable-element-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!