AngularJS : How to pass data from directive to controllers function

All we need is an easy explanation of the problem, so here it is.

I’m trying to pass some data from directive into a function addTrackFromPicker in my controller.

$scope.addTrackFromPicker = function (message) {
    console.log("addTrackFromPicker", message);
};

Here what I have in my directive

dir.directive('youtubeList', function($http, $timeout, YT_event){
    return {
        restrict: 'E',
        scope: {
            search: '=',
            dial: '&'
        },
        templateUrl: 'youtube-list.html',
...

Here I want to call controllers function from my template and pass it item.id.$t as argument:

<div class="media list-group-item" ng-repeat="item in entries">
<a type="button" ng-click="dial(item.id.$t)">
    <img  ng-src="{{item.media$group.media$thumbnail[0].url}}">
</a>

But I don’t know how to pass it into my tag

<youtube-list search="search" dial="addTrackFromPicker(???)"></youtube-list>

I also tried $parent.addTrackFromPicker but it didnt work

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In order to pass in your data from your directive, you will need to do it like this:

<youtube-list search="search" dial="addTrackFromPicker(data)"></youtube-list>

Then, in your template:

<div class="media list-group-item" ng-repeat="item in entries">
    <a type="button" ng-click="dial({data: item.id.$t})">
        <img  ng-src="{{item.media$group.media$thumbnail[0].url}}">
    </a>
</div>

You can use an “argument name” other than data if something else makes more sense for your situation. See Angular’s documentation on scope for detailed info on how this works.

Method 2

Isolated Scope: pass some values from the parent scope to the directives

There’re 3 types of prefixes AngularJS provides

  1. “@” ( Text binding / one-way binding )
  2. “=” ( Direct model binding / two-way binding )
  3. “&” ( Behaviour binding / Method binding )

All these prefixes receives data from the attributes of the directive element.

 class="directive"

 name="{{name}}"

 color="color"

When the directive encounters a prefix in the scope property, it will look for an attribute ( with same property name ) on directive’s html element

 scope : {    
  name: "@"    
 }

I’ve followed this linkhttp://jsfiddle.net/shidhincr/pJLT8/10/light/

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply