codememo

각도의 ng클릭 이벤트 위임

tipmemo 2023. 3. 19. 18:16
반응형

각도의 ng클릭 이벤트 위임

100리씩의 ul이 있는 경우 각 li에 ng-clicks가 존재해야 합니까?아니면 이벤트를 ul에 바인드하여 jquery의 종류에 위임할 수 있는 방법이 있습니까?이게 더 나을까요, 아니면 더 나을까요?100개의 이벤트를 하는 건가요? 아니면 결국 하나의 이벤트만 하는 건가요?

angular는 리피터와는 이벤트 위임을 하지 않는 것 같습니다.누군가가 그것에 대한 기사를 기투브에서 개설했다.논쟁은 그것이 실제로 더 나은 성과로 이어질 것인가 하는 것입니다.

회피책이 있을 수 있지만 jQuery가 필요합니다.부모 요소에서 사용할 특수 지시문을 작성하고 돔 노드에 리스너를 등록하는 것으로 구성됩니다.

다음 예시는 하위 노드를 클릭할 때 호출되는 함수 이름과 수신할 하위 노드를 식별하는 데 도움이 되는 선택 도구입니다.Angular의 jquery 구현은 우리에게 오직bindmethod - 이벤트청취자를 실제 엘리먼트에 등록하는 것으로 한정됩니다.jQuery를 로드하여 다음 중 하나에 액세스해야 합니다.on또는delegate방법.

HTML

<ul click-children='fun' selector='li'>
    <li ng-repeat="s in ss" data-index="{{$index}}">{{s}}</li>
</ul>

정의된 함수는 컨트롤러에 정의되어 있으며 인덱스가 전달될 것으로 예상됩니다.

$scope.fun = function(index){
    console.log('hi from controller', index, $scope.ss[index]);      
};

이 지시어는$parse표현식을 이벤트청취자에서 호출되는 함수로 변환합니다.

app.directive('clickChildren', function($parse){
  return {
    restrict: 'A',
    link: function(scope, element, attrs){       
      var selector = attrs.selector;
      var fun = $parse(attrs.clickChildren);   
      element.on('click', selector, function(e){       
        // no need to create a jQuery object to get the attribute 
        var idx = e.target.getAttribute('data-index');        
        fun(scope)(idx);        
      });
    }
  };
});

Pluker: http://plnkr.co/edit/yWCLvRSLCeshuw4j58JV?p=preview


주의: 격리된 스코프를 사용하여 명령어에 함수를 위임할 수 있습니다.{fun: '&'}볼만한 가치가 있지만, 복잡성이 증가합니다.

여기서 jm-의 예를 참고하여 이 지시문의 보다 간결하고 유연한 버전을 작성했다.나도 같이 먹을까?크레딧은 jm-;)로 이동합니다.

버전에서는 함수명을 $scope[fn](e, data)로 호출하려고 하거나 정상적으로 실패합니다.

클릭된 요소에서 선택적 json 개체를 전달합니다.그러면 각도 식을 사용하여 호출되는 메서드에 여러 속성을 전달할 수 있습니다.

HTML

<ul delegate-clicks="handleMenu" delegate-selector="a">
  <li ng-repeat="link in links">
    <a href="#" data-ng-json='{ "linkId": {{link.id}} }'>{{link.title}}</a>
  </li>
</ul>

자바스크립트

컨트롤러 방식

$scope.handleMenu = function($event, data) {
  $event.preventDefault();
  $scope.activeLinkId = data.linkId;
  console.log('handleMenu', data, $scope);
}

디렉티브 컨스트럭터

// The delegateClicks directive delegates click events to the selector provided in the delegate-selector attribute.
// It will try to call the function provided in the delegate-clicks attribute.
// Optionally, the target element can assign a data-ng-json attribute which represents a json object to pass into the function being called. 
// Example json attribute: <li data-ng-json='{"key":"{{scopeValue}}" }'></li>
// Use case: Delegate click events within ng-repeater directives.

app.directive('delegateClicks', function(){
  return function($scope, element, attrs) {
    var fn = attrs.delegateClicks;
    element.on('click', attrs.delegateSelector, function(e){
      var data = angular.fromJson( angular.element( e.target ).data('ngJson') || undefined );
      if( typeof $scope[ fn ] == "function" ) $scope[ fn ]( e, data );
    });
  };
});

기여하고 싶은 사람이 있다면 피드백을 듣고 싶습니다.

handle Menu 메서드는 좀 더 복잡한 어플리케이션에서 추출했기 때문에 테스트하지 않았습니다.

위의 BradGreens의 design Clicks에서 handleMenu 함수를 $scope.tomato.handleMenu로 더 깊이 배치할 수 있는 몇 가지 코드를 수정했습니다.

app.directive('delegateClicks', function () {
    return function ($scope, element, attrs) {
        var fn = attrs.delegateClicks.split('.').reduce(function ($scope, p) { return $scope[p] }, $scope); 
        element.on('click', attrs.delegateSelector, function (e) {
            var data = angular.fromJson(angular.element(e.target).data('ngJson') || undefined);
            if (typeof fn == "function") fn(e, data);
        });
    };
});

GitHub의 이슈에 따르면 이벤트 처리를 위임하는 것은 성능상 이점이 없습니다.

간단히 .ng-click는 "Directive"라는 사용합니다.$index , , , , 입니다.$event:

<ul>
   <li ng-repeat="item in collection"
       ng-click="lineClicked(item, $index, $event)">
      {{item}}
   </li>
</ul>
$scope.lineClicked = function(item, index, event) {
    console.log("line clicked", item, index);
    console.log(event.target)
});

상세한 것에 대하여는, 을 참조해 주세요.

언급URL : https://stackoverflow.com/questions/13965627/angular-ng-click-event-delegation

반응형