本文介绍了AngularJS 指令绑定具有多个参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将控制器中定义的函数与指令中的回调函数绑定时遇到了一些问题.我的代码如下所示:

I'm having some trouble binding a function defined in a controller with a callback function in a directive. My code looks like the following:

在我的控制器中:

$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 页面中:

And in my html page:

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

上面的代码没有运气.根据我在各种教程中阅读的内容,我明白我应该在 HTML 页面中指定参数?

Having no luck with the code above. From what I've read in various tutorials I understand I'm supposed to specify the arguments in the HTML page?

推荐答案

你的代码有一个小错误,请试试下面的代码,它应该对你有用

There is one small mistake in your code, please try the code below and it should work for you

<!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>

这篇关于AngularJS 指令绑定具有多个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:32