I've got the following directive:
template: '<div data-div="outer"><div data-div="inner"></div></div>',
link: function postLink(scope, elem, attrs) {
var outer = elem.find('[data-div="outer"]');
var inner = elem.find('[data-div="inner"]');
outer.css({
'background': 'red',
'width': "100%",
'height': "100%",
});
inner.css({
'background': 'blue',
'width': "50%",
'height': "100%",
});
}
Based on this post, i tried these selectors. but im using jQLite, not JQuery.
so, how to find an element based on a data-attribute value?
I've got the following directive:
template: '<div data-div="outer"><div data-div="inner"></div></div>',
link: function postLink(scope, elem, attrs) {
var outer = elem.find('[data-div="outer"]');
var inner = elem.find('[data-div="inner"]');
outer.css({
'background': 'red',
'width': "100%",
'height': "100%",
});
inner.css({
'background': 'blue',
'width': "50%",
'height': "100%",
});
}
Based on this post, i tried these selectors. but im using jQLite, not JQuery.
so, how to find an element based on a data-attribute value?
http://plnkr.co/edit/FeJWvwnKjOZwAIABigtA?p=preview
Share Improve this question edited May 23, 2017 at 10:29 CommunityBot 11 silver badge asked Sep 8, 2014 at 4:37 rnrneverdiesrnrneverdies 15.7k9 gold badges66 silver badges95 bronze badges2 Answers
Reset to default 5You can use querySelector()
(or querySelectorAll()
for multiples) to get a similar find()
behavior when using jqLite...
function postLink(scope, elem, attrs) {
var outer = angular.element(elem[0].querySelector('[data-div="outer"]'));
var inner = angular.element(elem[0].querySelector('[data-div="inner"]'));
outer.css({
'background': 'red',
'width': "100%",
'height': "100%",
});
inner.css({
'background': 'blue',
'width': "50%",
'height': "100%",
});
}
Demo Plunker
In angular, you rarely ever have to use jQuery selectors to find elements. Angular will walk the DOM tree and find the directives for you.
All you have to do is implement the directives:
app.directive('div', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
if(attr.div == 'outer') {
element.css({
'background': 'red',
'width': "100%",
'height': "100%",
});
}
if(attr.div == 'inner') {
element.css({
'background': 'blue',
'width': "50%",
'height': "100%",
});
}
}
}
});
If you need further interactions with the parent directive, angular makes that easy to do too. You just have include a require attribute to your directive definition, and the parent controller will be injected as the 4th parameter to your child directive's link function:
app.directive ('parent', function() {
return {
...
controller: function($scope, $element, $attrs) {
function doSomething() {
}
}
}
});
app.directive('child, function() {
return {
restrict: 'A',
require: '^parent', // child directive requires a parent directive
link: function(scope, element, attr, parentController) {
// access to the parent controller
parentController.doSomething();
}
}
});