【问题标题】:AngularJS directive binding a function with multiple argumentsAngularJS指令绑定具有多个参数的函数
【发布时间】:2020-06-09 11:15:34
【问题描述】:

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

在我的控制器中:

$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 页面中指定参数?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    可以在缩小后继续使用的替代方法

    让你的 html 保持原样:

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

    将调用改为:

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

    注意onDrop 的额外左括号和右括号。这将实例化函数而不是注入函数的代码。

    为什么更好

    1. 更改handleDrop() 定义中的参数名称(或者甚至添加更多,如果处理正确的话)不会使您更改html 中的每个指令注入。非常干燥。

    2. 正如@TrueWill 建议的那样,我几乎可以肯定其他解决方案无法在缩小后继续存在,而这种方式代码保持最大的灵活性并且与名称无关。

    另一个个人原因是对象语法,这让我写了很多代码:

    functionName({xName: x, yName: y}) // (and adding the function signature in every directive call)
    

    相对

    functionName()(x,y) // (zero maintenance to your html)
    

    我找到了这个很棒的解决方案here

    【讨论】:

    • 这也适用于我,但我在使用对象表示法时遇到了问题。在 Typescript 中显式使用类。 this comment 帮我修好了。
    • 这行得通。通过执行 Joe 的操作,我得到了“TypeError:无法使用 'in' 运算符在 y 中搜索 x”。
    【解决方案2】:

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

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

    【讨论】:

    • Angular 文档中在哪里定义了这种行为?
    • 文档中似乎没有真正的主题,但主题是指令的链接功能,docs.angularjs.org/guide/directive
    • 显然参数名称必须与标记完全匹配;我想知道这是否会在缩小后幸存下来?
    • @TrueWill 我认为 AngularJS 完全与传统的缩小作斗争,但它确实有一个 ngmin 模块可以做同样的事情
    • @JosephPaterson 根据网页,ngmin 已被弃用,取而代之的是 ng-annotate。谢谢!
    猜你喜欢
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多