Angular Directive使用&不将参数传递给控制器​​来绑定函数

yve*_*era 13 javascript angularjs angularjs-directive

我有一个与Box文件选择器交互的指令.我的指令由2个独立的控制器使用,可能在将来增加更多.

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

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

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

我创建了一个plunkr,我在嘲笑Box选择行为

调节器

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

指示

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();
        });

      }
    };
  });
Run Code Online (Sandbox Code Playgroud)

视图

<div ng-controller="myController">
  <button my-directive success="onSuccessful(arg)">Test</button>
</div>
Run Code Online (Sandbox Code Playgroud)

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

我能够通过使用'='代替'&'来解决这个问题,但我想知道为什么它不能与'&'一起工作,因为它应该用于方法绑定

Pau*_*tes 17

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

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

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

scope.success(message);
Run Code Online (Sandbox Code Playgroud)

通过:

scope.success({message:message.foo});
Run Code Online (Sandbox Code Playgroud)

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

 <button my-directive success="onSuccessful(arg)">Test</button>
Run Code Online (Sandbox Code Playgroud)

通过:

<button my-directive success="onSuccessful(message)">Test</button>
Run Code Online (Sandbox Code Playgroud)

你可以看到Working Plunker

  • 这很有效,非常感谢!我在官方文档中找不到这个文档,这看起来有点反直觉,为什么他们不能让我传递一个真正的函数而不是奇怪的代理函数? (2认同)