Reputation: 15657
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
Upvotes: 2
Views: 15491
Reputation: 52867
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();
}
}
});
Upvotes: 0
Reputation: 37530
You 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%",
});
}
Upvotes: 5