I am converting some code to use angular directives. I am new at this..
The old code is:
$('.header .mobile-nav ').append($('.navigation').html());
$('.header .mobile-nav li').bind('click', function(e) {
var $this = $(this);
var $ulKid = $this.find('>ul');
var $ulKidA = $this.find('>a');
if ($ulKid.length === 0 && $ulKidA[0].nodeName.toLowerCase() === 'a') {
window.location.href = $ulKidA.attr('href');
}
else {
$ulKid.toggle(0, function() {
if ($(this).css('display') === 'block') {
$ulKidA.find('.icon-chevron-down').removeClass('icon-chevron-down').addClass('icon-chevron-up');
}
else {
$ulKidA.find('.icon-chevron-up').removeClass('icon-chevron-up').addClass('icon-chevron-down');
}
});
}
e.stopPropagation();
return false;
});
My attempt at creative the correct directives is as follows:
app.directive('mobilenav', function () {
return { template: $('.navigation').html() };
});
app.directive('mobileNavMenu', function () {
var directive = {
link: link,
restrict: 'A'
};
return directive;
function link(scope, element, attrs) {
var iElement = element.find('.header .mobile-nav li');
iElement.bind('click', function (e) {
var $this = $(this);
var $ulKid = $this.find('* > ul');
var $ulKidA = $this.find('* > a');
if ($ulKid.length === 0 && $ulKidA[0].nodeName.toLowerCase() === 'a') {
window.location.href = $ulKidA.attr('href');
} else {
$ulKid.toggle(0, function () {
if ($(this).css('display') === 'block') {
$ulKidA.find('.icon-chevron-down').removeClass('icon-chevron-down').addClass('icon-chevron-up');
} else {
$ulKidA.find('.icon-chevron-up').removeClass('icon-chevron-up').addClass('icon-chevron-down');
}
});
}
e.stopPropagation();
return false;
});
}
});
The "click" event is not being bound. I think it could be because it is not finding the element. Am I using the right approach? Can you help me fix my directives?
Thanks!
I think there are a few things you could be doing better with this approach. First, I don't think your directives should searching for or modifying other elements by CSS.
So first I would modify this directive to bind directly on the passed in element:
function link(scope, element, attrs) {
//var iElement = element.find('.header .mobile-nav li');
iElement.bind('click', function (e) {
...
This might mean you need to apply your directive to a different element than you were originally intending.
Next, for the section where you toggle the chevrons, I think you might want to do this differently. You could for example, set a variable in the scope, or in a service, and then create another directive that watches that variable and responds to the changes in it. Alternatively, you might be able to use ng-show/ng-hide to elements based on the change.
These questions might be helpful to you as well:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.