javascript - Obtain access to a controller from a child directive in AngularJS -
i have small angular application needs list list of entities (endpoints in case). entities saved in array. purpose of example, let's they're on controller.
to better separate logic, created 2 directives: endpointlist
, endpoint, this:
the directives declared this:
myapp.directive('endpointlist', function () { return { restrict:'ea', controller:'endpointctrl', controlleras:'epctrl', transclude: true, replace: true, templateurl: 'endpoint-list.html' }; }) .directive('endpoint', function ($compile, $log) { return { scope: { scope:'=ngmodel', func:'&', index:'@' }, restrict:'ea', replace:true, templateurl: 'endpoint.html', require:'?^endpointlist', compile: function(telem, tatt) { return function(scope, el, attr, ctrl) { // ctrl.addresource(scope); } } }; });
the template endpoint-list.html
... <section> <table class="table table-hover"> <thead> <tr> <th><input type="checkbox" ng-model="selectall" ng-click="toggleselectall()"/></th> <th>label</th> <th>last updated</th> <th>status</th> <th>sync</th> </tr> </thead> <tbody ng-transclude></tbody> </table> </section> ...
the template endpoint.html
:
... <td> <a ng-click="sync()" class="glyphicon glyphicon-cloud">call me</a> </td> ...
and use them this:
<endpoint-list> <endpoint ng-repeat="ep in endpoints" scope="ep" ng-model="ep" func="selectep(scope)" index="{{$index}}"></end-point> </endpoint-list>
my problem in endpoint.html have link that, when clicked, want call function sync() on controller:
$scope.sync = function(endpoint) { console.log('syncing:'); console.log(endpoint); };
how can that? tips appreciated.
here's plunkr: http://plnkr.co/edit/js7syyz8u0i9kooigwdq
you can create service middle man, inject in both controller , directive, , that's it. you'll able call service's method directly directive's template, provided controller has reference service.
myapp.service("middlemanservice", function() { this.sync = function(endpoint) { console.log('syncing:'); console.log(endpoint); }; this.test = 'blah'; this.selectall = false; this.deletebtnvisible = false; this.editbtnvisible = false; this.endpoints = [ { label: '2.2.0', url: 'https://version-2_2_0-api.company.com/test/test?api_key=xxx', selected: false }, { label: '2.3.0', url: 'https://version-2_3_0-api.company.com/test/test?api_key=xxx', selected: false } ]; }; });
add reference service controller :
myapp.controller('endpointctrl', function ($scope, middlemanservice) { $scope.middlemanservice = middlemanservice;
and in html, call :
<td> <a ng-click="middlemanservice.sync()" class="glyphicon glyphicon-cloud">call me</a> </td>
Comments
Post a Comment