Pass callback function to directive

后端 未结 4 882
失恋的感觉
失恋的感觉 2020-12-09 04:00

I\'m trying to pass a callback function from a controller to a directive.

Here\'s the callback function code:

$scope.onImageSelect = function(image)          


        
相关标签:
4条回答
  • 2020-12-09 04:41

    try to change the scope object to be like this

    scope: {
            callback: '='
        }
    

    and it will work

    0 讨论(0)
  • 2020-12-09 04:46

    While calling the expression method from the directive you need to pass the parameter from the directive in JSON format, also you should correct your directive callback attribute value to pass function like callback="onImageSelect(image)"

    Directive usage:

    <google-image-search callback="onImageSelect(image)" />
    

    Directive Template

    <a data-ng-click="callback({image: url})"></a>
    
    0 讨论(0)
  • 2020-12-09 04:46

    Following code is tested and working..

    Directive call in html
    
    <taxcode-picker call-back-fun="calculate_tax(a, b)"></taxcode-picker>
    

    Sample Directive code

    {
    scope:'&',
    link: function (scope, element, attrs) {
     scope.tax = {amount:12, rate:10.50};
     scope.obj = {number:12, value:10};
    
      scope.call_back = function (tax) {
        scope.callBackFun({a:tax, b:obj});
      }
    }
    
    }
    

    Sample Controller

    app.controller("sample", function($scope){
    $scope.calculate_tax = function (tax, obj) {
    
            console.log("tax "+JSON.stringify(tax));
    
            console.log("obj "+JSON.stringify(obj));
        }
    });
    
    0 讨论(0)
  • 2020-12-09 04:58

    Simply use:

    <google-image-search callback="onImageSelect(image)" />
    

    This example from AngularJS developer guide is pretty similar to your case: http://plnkr.co/edit/hYBxk070sgw54RElyWNq?p=preview

    0 讨论(0)
提交回复
热议问题