/angularjs/

Two ways to pass function to directive.

2015-04-19 23:58:22

Lets suppose that you have some directive and your parent controller provide method that you want to use in your directive.

You can use this in two ways.

But first things first. Parent controller

.controller('someCtrl', function ($scope) {

    $scope.people = [];

    $scope.addPerson = function (name, lastName) {

        $scope.people.push({
            name: name,
            lastName: lastName
        });

        console.log("name = ", name, "lastName = ", lastName);
    };
})

And you want to use addPerson in your custom directive.

You can do something like this, I think, this is a standard way


<div 10px&quot;="" class='"col-xs-12"' style='"padding-top:'>
<my-directive-two call-back='"addPerson(paramA,' paramb)&quot;=""></my-directive-two>
</div>

addPerson(paramA, paramB) you can treat this as description of method interface

.directive('myDirectiveTwo', function () {
    return {
        scope: {
            callBack: '&amp;'
        },
        controller: function ($scope) {

            $scope.doAction = function () {
                $scope.callBack({paramA: 'michal 2', paramB: 'szalkowski 2'});
            };

        },
        templateUrl: 'my-directive-two.html'
    }
})

my-directive-two.html

<a btn-success&quot;="" class='"btn' ng-click='"doAction()"'>doAction</a>
<a 4',paramb:'szalkowski="" 4'})&quot;="" btn-success&quot;="" class='"btn' ng-click="&quot;callBack({paramA:'michal">callBack</a>

as I said this is standard way, but there is always something more

double brackets way


<div class='"col-xs-12"'>
<my-directive-one call-back='"addPerson"'></my-directive-one>
</div>

.directive('myDirectiveOne', function () {
    return {
        scope: {
            callBack: '&amp;'
        },
        controller: function ($scope) {

            $scope.doAction = function () {
                $scope.callBack()("michal 1", "szalkowski 1");
            };

        },
        templateUrl: 'my-directive-one.html'
    }
})

my-directive-one.html

<a btn-success&quot;="" class='"btn' ng-click='"doAction()"'>doAction</a>
<a 3')&quot;="" 3','szalkowski="" btn-success&quot;="" class='"btn' ng-click="&quot;callBack()('michal">callBack</a>