简体   繁体   中英

How to pass a function handler from controller into directive isolated scope in AngularJs?

I have the following function in controller:

  angular.module('app').controller('BodyController', function(){
    this.click = function(message){
      alert(message);
    }
  })

I want to pass this function into directive's isolated scope to call it with some specific params, something like that:

  angular.module('app').directive('custom', function(){
    return {
      restrict: 'A',
      scope: {
        text: '@',
        click: '&click'
      },
      link: function(scope, element){
        //...
        scope.click('Hello, Plunker!');
        //...
      }
    }
  })

And I pass thefunction in this way:

<h1 custom text="Hello Plunker!" click="ctrl.click"></h1>

Here is an example: http://plnkr.co/edit/4zkxuHJIB3D339h2Oy60?p=preview

The function is not called. What am I missing?

Thanks in advance

By using click: '&click' (which can be shortened to just click: '&' ), you're saying "make click on the inner scope execute the expression in 'click' attribute". That means that you need to actually call the method in the expression, not just point to it.

<h1 click="ctrl.click()">...</h1>

If, on the other hand you want to get a reference to the outer function and then play with it (eg pass arguments to it), you need to get it using:

scope: {
    click: '='
}

or just use solution by @michael-zuchetta, which was new to me :)

you can do something like

 angular.module('app').directive('custom', function(){
    return {
      restrict: 'A',
      scope: {
        text: '@',
        click: '=click'
      },
      link: function(scope, element){
      //  console.dir(scope.click);
      element.bind("click",function(){

         scope.click('Hello, Plunker!');
      });

        element.text('Hello, Plunker!');
      }
    }
  })

here you get click function from parent scope by click: '=click'

and bind that function to click on the element.

here is plnkr http://plnkr.co/edit/Ekw8I6Kg6tDOnIrnv4za?p=preview

or you can just pass the parameter into your directive like this http://plnkr.co/edit/mBbZil1jc4El2Jk79ru7?p=preview

This is a solution:

<h1 custom text="Hello Plunker!" click="click(message)"></h1>

Add the message parameter and then bind it :

 scope.click({message: "Hello Plunker:"});

This is the working example: http://jsfiddle.net/u748hLvn/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM