I am working in a directive and I am having problems using the parameter element
to find its childs by class name.
.directive("ngScrollList", function(){ return { restrict: 'AE', link: function($scope, element, attrs, controller) { var scrollable = element.find('div.list-scrollable'); ... } }; })
I can find it by the tag name but it fails to find it by class name as I can see in the console:
element.find('div') [<div class="list-viewport">…</div>,<div class="list-scrollable">…</div>] element.find('div.list-scrollable') []
Which would be the right way of doing such thing? I know I can add jQuery, but I was wondering if wouldn't that be an overkill....
In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the . directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive.
Using attrs you are able to access the attributes defined in your html tag like <fm-rating ng-model="$parent.restaurant.price" symbol="$" readonly="true"> So in this case you will have access to the symbol and readonly attributes.
AngularJS provides support to create custom directives for following type of elements. Element directives − Directive activates when a matching element is encountered. Attribute − Directive activates when a matching attribute is encountered. CSS − Directive activates when a matching css style is encountered.
Note: When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option. The restrict option is typically set to: 'A' - only matches attribute name.
jQlite (angular's "jQuery" port) doesn't support lookup by classes.
One solution would be to include jQuery in your app.
Another is using QuerySelector
or QuerySelectorAll
:
link: function(scope, element, attrs) { console.log(element[0].querySelector('.list-scrollable')) }
We use the first item in the element
array, which is the HTML element. element.eq(0)
would yield the same.
FIDDLE
In your link function, do this:
// link function function (scope, element, attrs) { var myEl = angular.element(element[0].querySelector('.list-scrollable')); }
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
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