【问题标题】:Angular Directive bind function with & not passing arguments to controllerAngular Directive绑定函数与&不将参数传递给控制器
【发布时间】:2015-08-13 21:56:26
【问题描述】:

我有一个与Box file picker 交互的指令。我的指令被 2 个独立的控制器使用,将来可能会添加更多。

Box 文件选择器可让您在用户选择文件/文件夹后设置回调函数,如下所示:

var boxSelect = new BoxSelect();
// Register a success callback handler
boxSelect.success(function(response) {
    console.log(response);
});

我的控制器正在使用该指令,它们将成功回调逻辑作为范围变量,我将其传递给该指令。

我创建了一个 plunkr 来模拟 Box 选择行为

控制器

.controller('myController', function($scope) {
  $scope.onSuccessful = function(message) {
    alert('Success! Message: ' + message);
  };
})

指令

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.onSuccessful = function(message) {
      //message is undefined here
      alert('Success! Message: ' + message);
    };
  })
  .directive('myDirective', function() {
    return {
      restrict: 'A',
      scope: {
        success: '&'
      },
      link: function(scope, element) {

        //third party allows to subscribe to success and failure functions
        function ThirdPartySelect() {

        }

        ThirdPartySelect.prototype.success = function(callback) {
          this.callback = callback;

        };

        ThirdPartySelect.prototype.fireSuccess = function() {
          this.callback({
            foo: 'bar'
          });
        };

        var myThirdPartyInstance = new ThirdPartySelect();
        myThirdPartyInstance.success(function(message) {
          //message is still defined here, but not in the controller
          scope.success(message);
        });

        element.on('click', function() {
          myThirdPartyInstance.fireSuccess();
        });

      }
    };
  });

查看

<div ng-controller="myController">
  <button my-directive success="onSuccessful(arg)">Test</button>
</div>

回调函数在控制器内部被调用,但参数 是未定义的。

我可以通过使用“=”而不是“&”来解决这个问题,但我想知道为什么它不能使用“&”,因为它应该用于method binding

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    是的,要将控制器函数绑定到您的指令,您必须使用 &amp; 绑定(表达式绑定),它允许指令调用由 DOM 属性定义的表达式或函数.

    但是在您的指令中,当您调用绑定方法时,函数参数应该是一个对象,其中键与您在定义函数时在控制器中声明的参数相同。

    所以在你的指令中,你必须替换:

    scope.success(message);
    

    作者:

    scope.success({message:message.foo});
    

    然后在你的 HTML 中,你必须替换:

     <button my-directive success="onSuccessful(arg)">Test</button>
    

    作者:

    <button my-directive success="onSuccessful(message)">Test</button>
    

    你可以看到Working Plunker

    【讨论】:

    • 参数名称应与html中的表达式一致。在控制器中有一个形式参数,它可以有任何名称。所以不需要在html中重命名param,只需要在从指令发送时在对象中提供arg即可。 scope.success({arg:message.foo});
    • 成功了,非常感谢!我在官方文档中找不到这个文档,这似乎有点违反直觉,为什么他们不让我传递对函数的真实引用而不是奇怪的代理函数?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 2014-06-06
    • 2015-09-13
    相关资源
    最近更新 更多