I would like to hear the opinion of more experienced AngularJS developers on whether the following directive is best practice...
I was trying to make to make a directive that will include HTML that:
- Can include compiled elements (other directives, like ng-src in the example below)
- Interpolated values ({{ value }})
- Can include values/functions from the parent scope without modifying it (i.e. the directive has isolated scope)
Example usage:
<div ng-controller="Ctrl">
<tag>
<h1><a href="{{ url }}">{{ url }}</a></h1>
<img ng-src="{{ image }}" />
</tag>
</div>
Controller and directive implementation:
var testapp = angular.module('testapp', []);
var Ctrl = function($scope) {
$scope.url = "http://google.com";
$scope.image = "https://www.google.gr/images/srpr/logo4w.png";
};
testapp.directive('tag', function() {
return {
restrict: 'E',
transclude: true,
scope: { },
compile: function compile(tElement, tAttrs, transclude) {
return function(scope) {
transclude(scope.$parent, function(clone) {
tElement.append(clone);
});
}
}
}
});
Fiddle: http://jsfiddle.net/x5WcB/3/
link
here instead ofcompile
.link
gets passed the scope as the first argument. – Asad Apr 8 '14 at 16:27