I'm back to using AngularJS and I've forgotten everything. I have an div in my html view that contains a custom directive and the children DIVs have a ng-repeat
directive, this is my HTML:
<div class="row" data-custom-directive>
<div class="col-xs-2 main-nav-cell" data-ng-repeat="nav in mainNavigation.topNavi" data-url="{{ nav.link }}">
<div> {{ nav.name }} </div>
<div class="item-counter" data-ng-show="nav.value > 0"> {{ nav.value }} </div>
</div>
</div>
Now in my custom directive I wait for the ng-repeat
to complete then I loop through the children DIVs and perform certain tasks (some I have omitted here).
.directive('customDirective', function ($location, $timeout, $rootScope) {
'use strict';
return{
restrict: 'A',
link: function (scope, element) {
$timeout(function () {
var i,
list = angular.element(element),
cssCheck = function () {
for (i = 0; i < list[0].children.length; i++) {
/*
Here I wish to set a click event on the Child DIV
I have tried list.children()[i].click = fn & list.children()[i].bind('click' fn)
but nothing works!
*/
// if the class is there remove it...
if (list.children()[i].classList.contains('is-active')) {
list.children()[i].classList.remove('is-active');
}
// if there is a match add the class...
if ($location.url().indexOf(list[0].children[i].getAttribute('data-url')) > 0) {
console.log('match');
list.children()[i].classList.add('is-active');
}
}
};
$rootScope.$on('$routeChangeSuccess', function () {
cssCheck();
});
// original kickoff
cssCheck();
});
}
};
I want to assign a click event to the first child div (where I check the CSS) and perform certain tasks depending on the 'data-url' I don't really want to add a ng-click
directive to the child in my HTML. Can someone please advise me on how to add a click event to the child div?
Many thanks
If Using jQuery:
link: function (scope, element) {
$timeout(function () {
element.on('click', ':first', function () {
console.log('inside event handler of the first child)
})
})
}
If not using jQuery
link: function (scope, element) {
$timeout(function () {
angular.element(element).on('click', function (evt) {
var isFirstChild = (evt.target.parentElement.children[0] === evt.target);
if (isFirstChild) {
// do the stuff
}
});
})
}
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.