Raduken Raduken - 6 months ago 18
Javascript Question

how to apply a jquery code in angular directive

I need insert a jquery code in a angular component, this jquery was in the html so not good practice.

I tried create a new function there and insert my jquery code , the jquery it is working very well, but i don't know why, the function link is now broken and not working.

I am new using angular and js so i can't understand well , can someone help to solve this? explain what is wrong in the code and i broken the function above

Thank you.

jquery code I tried to apply

$('#close, #menu-toggle').click(function(e) {
e.preventDefault();
$('#wrapper').toggleClass('toggled');
});


angular file:

angular.module('test').directive('leftBar', [
'leftBarService',
function leftBar(leftBarService) {
'use strict';

var
scope = {
onLeafNode: '='
};

function link($scope, $element) {
$element.leftBar({
speed: 1000,
useDynamicLoading: false,
onLeafNodeReched: $scope.onLeafNode
});

}

function menu ($scope, $element){
$('#close, #menu-toggle').click(function(e) {
e.preventDefault();
$('#wrapper').toggleClass('toggled');
});
}

return {
restrict: 'A',
scope: scope,
link: link,
link:menu,
templateUrl: 'app/test/leftBar/leftBar.html'
};
}

]);

Answer

In the returning object of the directive you are using two links properties. You need to put the jQuery code you mention inside of the link function already declared and use just one link property in the returned object.

angular.module('test').directive('leftBar', [
  'leftBarService',
  function leftBar(leftBarService) {
    'use strict';

    var
      scope = {
        onLeafNode: '='
      };

    function link($scope, $element) {
      $element.leftBar({
        speed: 1000,
        useDynamicLoading: false,
        onLeafNodeReched: $scope.onLeafNode
      });

      menu();
    }

    function menu() {
      $('#close, #menu-toggle').click(function(e) {
        e.preventDefault();
        $('#wrapper').toggleClass('toggled');
      });
    }

    return {
      restrict: 'A',
      scope: scope,
      link: link,
      templateUrl: 'app/test/leftBar/leftBar.html'
    };
  }

]);