ShankarGuru
ShankarGuru

Reputation: 625

How to access scope in a nested directive?

I have a nested directive, where from the nested directive i am trying to pass a function to my controller.... the function is not being triggered.

This is my main directive html

<div class="panel panel-primary">
  <div class="panel-heading" ng-click="collapse()">{{user.name}}</div>
  <div class="panel-body" ng-hide="collapsed">
    <address></address>
    <div>
      <h4>Friends:</h4>
      <div ng-repeat="friend in user.friends">
        {{friend}}
        <remove-friend method="removeFri(friend)"></remove-friend>
      </div>
      <div ng-show="!!user.rank">
        {{user.rank}}
      </div>
      <button ng-show="!user.rank"  class="btn btn-primary" ng-click="knightme(user)">Click Me</button>
    </div>
  </div>
</div>

In the above directive i have a remove-friend directive which has a property named method and function referencing my controller function removeFri()

In my directive i am referencing it like this...

 .directive("removeFriend", function(){
      return {
        restrict: 'E',
        templateUrl: "removeFriend.html",
        scope : {
          method: "&"
        },
        controller: function($scope){
          $scope.remove = function(){
            $scope.method();
          };
        }
      };
  });

$scope.method() is never called, trying to put an alert($scope.method()) returns me undefined. Below is a plunker on clicking the x(remove icon), i need to remove the particular item.

https://plnkr.co/edit/d5fStmjspGm5AMmCK9Rx?p=preview

Upvotes: 2

Views: 92

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

The userInfoCard directive also has an isolated scope, and since you didn't pass it the function from the controller, it was undefined. You need to add it to the scope with = binding (since you don't know the parameter yet, and then it will work:

HTML:

<user-info-card user="user" collapse="true" remove-fri="removeFri"></user-info-card>

Directive:

scope: {
    user: '=',
    removeFri: '=',
    initiallyCollapsed: '@collapse'
},

Plnkr

Upvotes: 2

Related Questions