我正在尝试创建一个指令,通过使用"大","中","小"的下拉选择器来更改html元素类型(h1/h2/h3).我希望它也保留元素的属性.我创建了一个这个例子的小提琴:http: //jsfiddle.net/H63Z3/1/
角度:
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);
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
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: …Run Code Online (Sandbox Code Playgroud)