Skip to content

Instantly share code, notes, and snippets.

@dimorphic
Created January 15, 2015 17:54
Show Gist options
  • Save dimorphic/4209a78590667f91a6e6 to your computer and use it in GitHub Desktop.
Save dimorphic/4209a78590667f91a6e6 to your computer and use it in GitHub Desktop.
replicate behaviour of angular 'replace' in directives (will be removed in future angularjs versions)
/// Replace element with it's first child
Utils.replaceWithChild = function(element) {
var child = angular.element(element[0].firstChild);
Utils.mergeAttributes(element, child);
element.replaceWith(child);
}
/// Copy attributes from sourceElement to targetElement, merging their values if the attribute is already present
Utils.mergeAttributes = function(sourceElement, targetElement) {
var arr = sourceElement[0].attributes;
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(!item.specified)
continue;
var key = item.name;
var sourceVal = item.value;
var targetVal = targetElement.attr(key);
if(sourceVal === targetVal)
continue;
var newVal = targetVal === undefined
? sourceVal
: sourceVal + ' ' + targetVal;
targetElement.attr(key, newVal);
}
}
angular.module('test')
.directive('unwrap', function() {
return {
restrict: 'AE',
templateUrl: 'unwrap.part.html',
compile: function() {
return function postCompile(scope, element, attr) {
Utils.replaceWithChild(element);
};
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment