簡體   English   中英

Angular Directive使用&不將參數傳遞給控制器​​來綁定函數

[英]Angular Directive bind function with & not passing arguments to controller

我有一個與Box文件選擇器交互的指令。 我的指令由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>

回調函數在控制器內部被調用,但參數未定義。

我能夠通過使用'='代替'&'來解決這個問題,但我想知道為什么它不能與'&'一起工作,因為它應該用於方法綁定

是的,要將控制器函數綁定到指令,必須使用& bindings(表達式綁定),它允許指令調用由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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM