2016-08-16 5 views
0

작은 십자가의 아이콘이있는 지시문이 있습니다. 사용자가이 십자가를 클릭하면 콜백이 호출되어야합니다.AngularJS - 지시문 콜백에 대한 전달 전달

<div class="item" title="{{name}}"> 
    <button type="button" class="close"> 
    <span ng-click="onDelete()">&times;</span> 
    </button> 
    <span class="glyphicon glyphicon-folder-open"></span> 
</div> 

지침의 자바 스크립트 : 마지막으로

angular.module('hiStack').directive('hsItem', function() { 
    return { 
    restrict: 'E', 
    replace: true, 
    templateUrl: 'item.tpl.html', 
    scope: { 
     onDelete: '&', 
     title: '@' 
    } 
    }; 
}); 

, 지시어 사용하는 코드 :

<hs-item on-delete="deleteGroupModal = true" title="TestTitle"></hs-item> 

deleteGroupModal = true은 여기

는 지시 템플릿의 코드입니다 십자가를 클릭 할 때 결코 호출되지 않습니다. 대신 deleteGroup()과 같은 함수를 전달하면 작동합니다. 예를 들어 일반적으로 ng-click과 같이 과제를 전달하려면 어떻게해야합니까?

감사합니다.

+1

당신은 정의 할있는 기능을 작성하고 통과해야 : deleteGroupModal = true를하고 작동해야

는이 같은 속성에 전달 된 표현을 평가 후면 가능, 말했다. 함수를 선언하지 않으면 불가능합니다. &가 사용됩니다. –

+0

'ng-click = "test = true"'와 같은'ng-click' 지시자처럼 할 수 없습니까? – Mathieu

+0

"like ng-model directive"란 무엇을 의미합니까? ng-model에서는 조건없이 변수 ($ scope) 만 전달할 수 있습니다. –

답변

1

이고르 얀코비치 (Igor Janković)는 "속성에 직접 쓰는 것보다는 함수를 전달하는 것이 좋습니다.

angular.module('hiStack').directive('hsItem', function() { 
    return { 
    restrict: 'E', 
    replace: true, 
    templateUrl: 'item.tpl.html', 
    scope: { 
     title: '@' 
    }, 
    link: function(scope, element, attrs) { 
     scope.onDelete = function() { 
      // Eval the code on the parent scope because directive's scope is isolated in this case 
      if (attrs.onDelete) scope.$parent.$eval(attrs.onDelete); 
     } 
    } 
    }; 
}); 
관련 문제