angularjs - how to call a controller function from ng-click directive? -
i have 2 directives , controller, problem can't call function 'addmarkers()' of controller directive .
i have following codes:
derectives.js
app .directive('collection', function () { var tpl = '<ul><member ng-repeat="member in collection" member="member"></member></ul>'; return { restrict: "e", replace: true, scope: { collection: '=' }, template: tpl } }) app .directive('member', function ($compile) { var tpl = '<li><a ng-click="addmarkers(member)" >{{member.title}}</a>'+ '<input class="align" ng-if="!member.children" type="checkbox" ng-checked="true"/></li>'; return { restrict: "e", replace: true, scope: { member: '=' }, template: tpl, link: function (scope, element, attrs) { if (angular.isarray(scope.member.children)) { element.append("<collection collection='member.children'></collection>"); $compile(element.contents())(scope) } } } })
controller.js
app .controller('indexctrl', function($scope, itemprovider){ itemprovider.getitems().success(function(data){ $scope.items = data; }); $scope.addmarkers = function(item){ alert("helloo"); $scope.markers = itemprovider.addmarkers(); } });
index.html
<div id="menu" ng-controller="indexctrl"> <nav> <h2><i class="fa fa-reorder"></i>all categories</h2> <collection collection='items'></collection> </nav> </div>
$rootscope global scope should used when required. should kept clean possible avoid pollution of scope variables.
in order access parent method isolated scope can use $parent service, shown below:
scope.$parent.addmarkers();
example: basic example
in case, directive wants access parent again called inside directive,hence such cases can use $parent.$parent,
scope.$parent.$parent.addmarkers();
shown in following:
example:example case
this can done if number of directives using parent scope limited. if hierarchy long, using multiple $parent makes code clumsy. in cases, preferable add parent method inside service , call service directives.
example: service example
Comments
Post a Comment