Angular call controller method from directive template

I create simple project with angular and I use directive to create a simple grid like this code :

my directive :

app.directive('dpGrid',()=>{
    return{
        restrict:"E",
        scope:{
            items:"="
        }
        templateUrl: 'template/dbgrid.directive.html'
    }

});

my controller :

   app.controller('mainCtrl',($scope)=>{

$scope.data=[{fname:"david",lname:"orman",age:24,id:"234"}];

        $scope.update=(id)=>{
          console.log("ID :",id);
        };

    });

my directive template :

<table class="table">
    <thead class="thead-inverse">
    <tr>
        <th>#</th>
        <th>fname</th>
        <th>lname</th>
        <th>age</th>
        <th>opt</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="item in items" >
        <th>{{$index}}</th>
        <td>{{item.fname}}</td>
        <td>{{item.lname}}</td>
        <td>{{item.age}}</td>
        <td><a class="btn btn-danger" ng-click="update(item.id)">update</a></td>

    </tr>
    </tbody>
</table> 

and I use directive like this :

<dp-grid items="data" ></dp-grid>

I want call update() method from directive template, but dont call update() method when click on update btn

Answer

You simply need to specify the controller your directive should use, then access it in template.

return {
    restrict:"E",
    scope:{
        items:"="
    },
    controller: 'mainCtrl',
    templateUrl: 'template/dbgrid.directive.html'
}

Then you will be able to access the function in the templates. If you are accessing it from a child isolate scope, you may need to access it using $parent.

Leave a Reply

Your email address will not be published. Required fields are marked *