Reputation: 2404
I have a custom directive called side-menu, which I can use at my index.html as follows.
<side-menu></side-menu>
Inside the directive, there is a controller. This controller is in a separate file (SidebarController.js). Following is the template file of my directive:
<div class="sidebarContainer" ng-controller="SidebarController as sidebar">
...
</div>
This controller listens to mouse events in the directive. For example, following is a line from the controller:
angular.element('#sidebarContainer ul li').on('mouseleave', 'li.item > i', function ($event){...})
which listens to mouseleave event on a list item inside the directive. However, I have to carry this controller outside the directive, because it won't let me create an isolated scope on the directive. I changed the layout of my index.html as follows:
<div class="sidebarContainer">
<side-menu></side-menu>
</div>
The problem is, the controller no longer listens to anything inside the directive. All the DOM elements are still at same locations. But the controller only listens to them when I put it inside the directive. How can I solve this problem?
Upvotes: 1
Views: 820
Reputation: 1095
First of all AngularJs
will not be happy if you use DOM operations inside controllers. For that very reason we use directives
. So I suggest you use all DOM operation inside directives.
Also you can use event handlers provided by angular (eg. ng-mouseleave
in your case) instead of jquery way.
Also isolated scope could not catch methods and variables defined inside parent controller. For that purpose you can use $parent
property.
eg.
<li class="item" ng-mouseleave="$parent.mouseLeft('Item 1')"><i>Item 1</i></li>
https://plnkr.co/FWhus72HV7v7vTWfmBLQ
Upvotes: 3