programing

AngularJS - 함수를 지시어로 전달합니다.

iphone6s 2023. 2. 26. 09:19
반응형

AngularJS - 함수를 지시어로 전달합니다.

각진 예가 있습니다.JS

<div ng-controller="testCtrl">

<test color1="color1" updateFn="updateFn()"></test>
</div>
 <script>
  angular.module('dr', [])
.controller("testCtrl", function($scope) {
    $scope.color1 = "color";
    $scope.updateFn = function() {
        alert('123');
    }
})
.directive('test', function() {
    return {
        restrict: 'E',
        scope: {color1: '=',
                updateFn: '&'},
        template: "<button ng-click='updateFn()'>Click</button>",
        replace: true,
        link: function(scope, elm, attrs) { 
        }
    }
});

</script>
</body>

</html>

버튼을 클릭하면 경보 상자가 표시되지만 아무것도 표시되지 않습니다.

누가 나를 도와줄 수 있나요?

격리된 스코프 디렉티브 내부에서 부모 스코프의 컨트롤러 함수를 호출하려면 다음과 같이 합니다.dash-separatedOP에서 말한 것처럼 HTML에서 속성 이름을 지정합니다.

또한 함수에 파라미터를 전송하려면 객체를 전달하여 함수를 호출합니다.

<test color1="color1" update-fn="updateFn(msg)"></test>

JS

var app = angular.module('dr', []);

app.controller("testCtrl", function($scope) {
    $scope.color1 = "color";
    $scope.updateFn = function(msg) {        
        alert(msg);
    }
});

app.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            color1: '=',
            updateFn: '&'
        },
        // object is passed while making the call
        template: "<button ng-click='updateFn({msg : \"Hello World!\"})'>
            Click</button>",
        replace: true,        
        link: function(scope, elm, attrs) {             
        }
    }
});

Fiddle

제가 뭔가 놓치고 있는 것 같습니다만, 다른 솔루션에서는 부모 스코프 함수를 호출하고 있습니다만, 디렉티브코드에서 인수를 건네주는 기능은 없습니다만, 이것은,update-fn호출하고 있다updateFn()예를 들어, 고정 파라미터를 사용하여{msg: "Hello World"}약간의 변경만 있으면 지시가 인수를 통과할 수 있기 때문에 훨씬 편리하다고 생각합니다.

<test color1="color1" update-fn="updateFn"></test>

HTML은 함수 참조를 전달하고 있습니다.즉, HTML은 함수 참조를 전달하지 않습니다.()괄호

JS

var app = angular.module('dr', []);

app.controller("testCtrl", function($scope) {
    $scope.color1 = "color";
    $scope.updateFn = function(msg) {        
        alert(msg);
    }
});

app.directive('test', function() {
    return {
        restrict: 'E',
        scope: {
            color1: '=',
            updateFn: '&'
        },
        // object is passed while making the call
        template: "<button ng-click='callUpdate()'>
            Click</button>",
        replace: true,        
        link: function(scope, elm, attrs) {       
          scope.callUpdate = function() {
            scope.updateFn()("Directive Args");
          }
        }
    }
});

위의 경우 HTML이 로컬 스코프를 호출합니다.callUpdate이 함수는 부모 스코프에서 updateFn을 'fet'하고 디렉티브가 생성할 수 있는 파라미터를 사용하여 반환된 함수를 호출합니다.

http://jsfiddle.net/mygknek2/

'test' 지시어 Html 태그에서 함수의 속성 이름은 camelCased가 아니라 대시 기반이어야 합니다.

그래서 - 대신:

<test color1="color1" updateFn="updateFn()"></test>

기입:

<test color1="color1" update-fn="updateFn()"></test>

이것은 directive 속성(update-fn 함수 등)과 함수의 차이를 구별하는 각도의 방법입니다.

양방향 바인딩으로 컨트롤러 기능을 전달하면 어떨까요?그런 다음 일반 템플릿과 동일한 방법으로 지시문을 사용할 수 있습니다(간단하게 하기 위해 관련 없는 부분을 제거했습니다).

<div ng-controller="testCtrl">

   <!-- pass the function with no arguments -->
   <test color1="color1" update-fn="updateFn"></test>
</div>

<script>
   angular.module('dr', [])
   .controller("testCtrl", function($scope) {
      $scope.updateFn = function(msg) {
         alert(msg);
      }
   })
   .directive('test', function() {
      return {
         scope: {
            updateFn: '=' // '=' bidirectional binding
         },
         template: "<button ng-click='updateFn(1337)'>Click</button>"
      }
   });
</script>

위의 방법을 시도해 보았기 때문에 이 문제에 착수했습니다만, 왠지 효과가 없었습니다.이제 완벽하게 작동합니다.

속성명에는 대시와 소문자를 사용합니다(다른 답변과 같음).

 <test color1="color1" update-fn="updateFn()"></test>

지시 범위에서는 "&" 대신 "="를 사용합니다.

 scope: { updateFn: '='}

그런 다음 다른 함수처럼 updateFn을 사용할 수 있습니다.

 <button ng-click='updateFn()'>Click</button>

잘했어!

"&"가 아닌 "=" 바인딩을 사용할 수 밖에 없었습니다.이상한 행동.

@JorgeGRC 답변 감사합니다.하지만 한 가지, "아마도" 부분은 매우 중요합니다.파라미터가 있는 경우 템플릿에도 파라미터를 포함해야 합니다.또한 현지도 지정해야 합니다.updateFn({msg: "Directive Args"}.

언급URL : https://stackoverflow.com/questions/18378520/angularjs-pass-function-to-directive

반응형