Angular communication between controllers and directives

前端 未结 3 1864
再見小時候
再見小時候 2021-01-21 05:29

I have this piece of code which allows a user to leave comments on a list of items. I created a directive and listen to keydown in order to let the user submit a comment if

3条回答
  •  轮回少年
    2021-01-21 05:57

    You generally don't want your directives knowing anything about your controller, so the best(Angular) way of communicating between controllers and directives is through bi-directional bindings.

    In your situation, I think best practice, again IMO, would be to create a directive for the button -- not the input. You'd tell the button which "input" (by id) to monitor. Something like:

    
    
    

    ETA: Here's what the directive would end up looking like

    http://plnkr.co/edit/HhEAUUq0IZvzblbRksBH?p=preview

    myApp.directive('defaultInput', function () {
        return {
            restrict:'A',
            link: function(scope, element, attrs) {
                attrs.$observe('defaultInput', function(value) {
                    var inputElement = angular.element(document).find('#' + value);
                    inputElement.bind('keydown', function(e) {
                        if (e.keyCode == 13) {
                            element.click();
                        }
                    });
                });
            }
        };
    });
    

    It could get tricky because the $observe callback will fire every time your controller's scope.items changes, so you'd need to somehow unbind and rebind (I know you're using jQuery, but I'm not seeing angular.unbind in the docs).

    Another option, if you wanted to stick closer to your original approach:

    http://plnkr.co/edit/3X3usJJpaCccRTtJeYPF?p=preview

    HTML

    
    

    JavaScript

    myApp.directive('enterFiresNextButton', function() {
      return function(scope, element, attrs){
        element.on('keydown', function(e){
          if(e.keyCode == 13) {
            element.next('button').click();
          }
        });
      }
    });
    

提交回复
热议问题