javascriptjqueryangularjsangularjs-directivejqlite

Listen event on 1st child in AngularJS directive using jqlite


I'm working on a side navigation, which has tree structure only one level deep.

Right now every thing is good, but instead of listening to events on the parent li I only want to listen on the 1st a tag.

app.directive('subNav', function($animate, $compile) {
    return {
        link : function(scope, element, attr, controller) {
			element.on('click', function(e){
				console.log(element);
				x = element;
				controller.toggleState();				
				$compile(element.contents())(scope);
				scope.$apply();
				/**x = element;
				e.stopPropagation();
				if(element.find('ul').hasClass('ng-hide')){
					$animate.removeClass(element.find('ul'), 'ng-hide');
					scope.$apply();
				} else {
					$animate.addClass(element.find('ul'), 'ng-hide');
					scope.$apply();
				}**/
			});
        },
        controller : [function(){
			var vm = this;
			vm.toggleState = function() {
				if(vm.state === "false"){
					vm.state = false;
				}
				vm.state = !vm.state;
			};
		}],
		controllerAs : "subNav",
		scope: {
			state: '@subNav'
		},
		bindToController: true
    };
});

<ul class="navigation">
					<li class="navigation-items active" sub-nav="false" >
						<a data="main-link"><i class="material-icons">perm_identity</i> Option 1</a>
						<ul class="sub-nav animate-hide" ng-hide="!subNav.state">
							<li><a><i class="material-icons bullet">fiber_manual_record</i> Item 1</a></li>
						</ul>
					</li>
  </ul>

enter image description here

What happens here is when I click on Option 1 the tree expands and closes but the big problem is even if I click on item 1 the tree closes as I'm listening to events on the entire element.


Solution

  • Got the solution as soon as I posted the question. Solved this by using.

    angular.element(element).find('a').first().on('click', function(e){.....})

    instead of

    element.on('click', function(e){.....})

    If any one posts a better solution, I'll accept that answer.