Is there a more "angular" way of selecting DOM elements inside a directive template? For example, say you have this directive:
app.directive("myDirective", function() { return { template: '<div><ul><li ng-repeat="item in items"></ul></div>', link: function(scope, element, attrs) { var list = element.find("ul"); } } });
I used the jQuery style selector to get a hold of the DOM <ul>
element rendered in my template. Is there a better way to do this?
I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:
{ template: '<div>' + '<div class="title">{{title}}</div>' + '<div class="body" ng-transclude></div>' + '</div>', link: function(scope, element, attrs) { // Title element var title = angular.element(element.children()[0]), // ... } }
You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.
Here is the directive:
app.directive("ngScopeElement", function () { var directiveDefinitionObject = { restrict: "A", compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { scope[iAttrs.ngScopeElement] = iElement; } }; } }; return directiveDefinitionObject; });
Usage:
app.directive("myDirective", function() { return { template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>', link: function(scope, element, attrs) { scope.list[0] // scope.list is the jqlite element, // scope.list[0] is the native dom element } } });
Some remarks:
scope.list
from myDirective
s postLink-Function, which you are very likely using anywayngScopeElement
uses a preLink-function, so that directives nested within the element having ng-scope-element
can already access scope.list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With