Program Club

여러 인수로 함수를 바인딩하는 AngularJS 지시문

proclub 2020. 11. 9. 21:31
반응형

여러 인수로 함수를 바인딩하는 AngularJS 지시문


컨트롤러에 정의 된 함수를 지시문의 콜백 함수와 바인딩하는 데 문제가 있습니다. 내 코드는 다음과 같습니다.

내 컨트롤러에서 :

$scope.handleDrop = function ( elementId, file ) {
    console.log( 'handleDrop called' );
}

그런 다음 내 지시 :

.directive( 'myDirective', function () {
    return {
      scope: {
        onDrop: '&'
      },
      link: function(scope, elem, attrs) {
        var myFile, elemId = [...]

        scope.onDrop(elemId, myFile);
      }
    } );

그리고 내 HTML 페이지에서 :

<my-directive on-drop="handleDrop"></my-directive>

위의 코드에 운이 없습니다. 다양한 자습서에서 읽은 내용에서 HTML 페이지에 인수를 지정해야한다는 것을 이해합니까?


코드에 작은 실수가 하나 있습니다. 아래 코드를 시도해보세요.

<!doctype html>
<html ng-app="test">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>

  </head>
 <body ng-controller="test" >    


<!-- tabs -->
<div my-directive on-drop="handleDrop(elementId,file)"></div>

 <script>
     var app = angular.module('test', []);

     app.directive('myDirective', function () {
         return {
             scope: {
                 onDrop: '&'
             },
             link: function (scope, elem, attrs) {
                 var elementId = 123;
                 var file = 124;
                 scope.onDrop({elementId:'123',file:'125'});

             }
         }
     });

     app.controller('test', function ($scope) {
         alert("inside test");
         $scope.handleDrop = function (elementId, file) {
             alert(file);
         }
     });

   </script>
</body>


</html>

축소에서 살아남을 대체 방법

HTML을 그대로 두십시오.

<my-directive on-drop="handleDrop"></my-directive>

호출을 다음으로 변경하십시오.

scope.onDrop()('123','125')

onDrop에 주어진 여분의 여는 괄호와 닫는 괄호를 확인하십시오. 이것은 함수의 코드를 삽입하는 대신 함수를 인스턴스화합니다.

더 나은 이유

  1. changing the parameters' names in the handleDrop() definition (or even adding some more, if you handle it correctly) will not make you change each of the directives injections in the html. much DRYer.

  2. as @TrueWill suggested, i'm almost sure the other solutions will not survive minification, while this way code stays with maximum flexibility and is name agnostic.

another personal reason is the object syntax, which makes me write much more code:

functionName({xName: x, yName: y})

(and adding the function signature in every directive call)

as oppose to

functionName()(x,y)

(zero maintenance to your html)

i found this great solution here.

hope that helps!

참고URL : https://stackoverflow.com/questions/18973507/angularjs-directive-binding-a-function-with-multiple-arguments

반응형