I need to write a jQuery function as a AngularJS directive but I don't know how to use specific jqLite functions (closest, find..) and $(this) inside my directive.
I've tried it like this:
jQuery Version:
$('.collapse-link').click(function () {
var ibox = $(this).closest('div.ibox');
var button = $(this).find('i');
var content = ibox.find('div.ibox-content');
content.slideToggle(200);
button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
ibox.toggleClass('').toggleClass('border-bottom');
setTimeout(function () {
ibox.resize();
ibox.find('[id^=map-]').resize();
}, 50);
});
My AngularJS directive:
.directive('iboxDirective', function($timeout){
return{
restrict: 'A',
scope: {},
link: function(scope, elem){
elem.on('click', function(){
var ibox = angular.element('div.ibox');
var button = angular.element('i');
var content = angular.element('div.ibox-content');
content.slideToggle(200);
button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
ibox.toggleClass('').toggleClass('border-bottom');
// This $timeout trick is necessary to run the Angular digest cycle
$timeout(function(){
ibox.resize();
ibox.find('[id^=map-]').resize();
});
});
}
}
});
The HTML file using the directive above:
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Aktivitäten</h5>
<div class="ibox-tools">
<a class="collapse-link" ibox-directive>
<i class="fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="ibox-content">
Content...
</div>
</div>
This way the directive triggers all ibox div's, but I want to trigger each one individually.
What am I doing wrong? Hope you can help me..
You shouldnt use angular that way.
It may work but your comment in your code already tells you the reason
// This $timeout trick is necessary to run the Angular digest cycle
if you manipulate the DOM with no angular observed function you can get unexpected results and loose "connection" between DOM elements and your $scope.
Im not sure if I'm analysed correctly what your function does but here is an example plunker how you can do it: link