javascript – Angular Directive绑定函数带有&不传递参数给控制器

前端之家收集整理的这篇文章主要介绍了javascript – Angular Directive绑定函数带有&不传递参数给控制器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个与 Box file picker交互的指令.我的指令由两个单独的控制器使用,有可能在将来添加更多.

一旦用户选择文件/文件夹,Box文件选择器就可以设置回调函数,如下所示:

  1. var BoxSelect = new BoxSelect();
  2. // Register a success callback handler
  3. BoxSelect.success(function(response) {
  4. console.log(response);
  5. });

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

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

调节器

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

指示

  1. angular.module('myApp',[])
  2. .controller('myController',function($scope) {
  3. $scope.onSuccessful = function(message) {
  4. //message is undefined here
  5. alert('Success! Message: ' + message);
  6. };
  7. })
  8. .directive('myDirective',function() {
  9. return {
  10. restrict: 'A',scope: {
  11. success: '&'
  12. },link: function(scope,element) {
  13.  
  14. //third party allows to subscribe to success and failure functions
  15. function ThirdPartySelect() {
  16.  
  17. }
  18.  
  19. ThirdPartySelect.prototype.success = function(callback) {
  20. this.callback = callback;
  21.  
  22. };
  23.  
  24. ThirdPartySelect.prototype.fireSuccess = function() {
  25. this.callback({
  26. foo: 'bar'
  27. });
  28. };
  29.  
  30. var myThirdPartyInstance = new ThirdPartySelect();
  31. myThirdPartyInstance.success(function(message) {
  32. //message is still defined here,but not in the controller
  33. scope.success(message);
  34. });
  35.  
  36. element.on('click',function() {
  37. myThirdPartyInstance.fireSuccess();
  38. });
  39.  
  40. }
  41. };
  42. });

视图

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

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

我使用’=’而不是’&’来解决这个问题,但我想知道为什么它不能与’&’因为它应该用于method binding

解决方法

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

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

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

  1. scope.success(message);

通过:

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

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

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

通过:

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

你可以看到Working Plunker

猜你在找的JavaScript相关文章