Using Angular, how do I bind a click event to an element and on click, slide a sibling element down and up?

后端 未结 4 1501
慢半拍i
慢半拍i 2020-12-15 20:02

I\'m working with Angular and I\'m having trouble doing something that I normally use jQuery for.

I want to bind a click event to an element and on click, slide a sib

4条回答
  •  借酒劲吻你
    2020-12-15 20:52

    app.directive('slideMySibling', [function(){
      // Runs during compile
      return {
        // name: '',
        // priority: 1,
        // terminal: true,
        // scope: {}, // {} = isolate, true = child, false/undefined = no change
        // controller: function($scope, $element, $attrs, $transclude) {},
        // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
        restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
        // template: '',
        // templateUrl: '',
        // replace: true,
        // transclude: true,
        // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
        link: function($scope, iElm, iAttrs, controller) {
          iElm.bind("click", function(){
             $(this).siblings('element').slideToggle();
          })
        }
      };
    }]);
    

    Usage would be something like

    Some sibling

    Note all the "code" above is just for the sake of example and hasn't been actually tested.

    http://plnkr.co/edit/qd2CCXR3mjWavfZ1RHgA

    Here's a sample Plnkr though as mentioned in the comments this isn't an ideal setup since it still has the javascript making assumptions about the structure of the view so ideally you would do this with a few directives where one requires the other or by using events (see $emit, $broadcast, $on).

    You could also have the directive create the children "programmatically" via JavaScript and circumvent the issue of not knowing what context the directive is being used in. There are a lot of potential ways to solve these issues though none of the issues will stop it from functionally working they are worth noting for the sake of re-usability, stability, testing, etc.

提交回复
热议问题