How to call controller function from ng-click directive?

I have two directives and a controller, the problem is that I cannot call the 'addMarkers ()' function of the controller from my directive.

i have the 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)
            }
        }



    }
})
      

Run codeHide result


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();
    }
   });
      

Run codeHide result


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>		
      

Run codeHide result


+3


source to share


2 answers


$ rootScope is a global scope and should only be used when needed. It should be as clean as possible to avoid contamination of the sphere variables.

To access the parent method from the isolated scope, you can use the $ parent service as shown below:

scope.$parent.addMarkers();

      

Example

: basic example

In your case, the directive that wants to access the parent is called again from another directive, so for such cases you can use $ parent. $ parent,



scope.$parent.$parent.addMarkers();

as shown below:

Example

: example for your case

This can be done if the number of directives using the parent scope is limited. If the hierarchy is long, then using multiple $ parent makes the code clunky. In these cases, it is preferable to add a parent method inside the service and call the service from directives.

Example: service example

+1


source


I have to use $ rootScope instead of $ scope like below,



$rootScope.addMarkers = function(item){
     alert("Helloo");
     $scope.markers = itemProvider.addMarkers();
}

      

0


source







All Articles