Angular call controller method from directive template Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Angular call controller method from directive template without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about Angular call controller method from directive template - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji