Rahi.Shah
Rahi.Shah

Reputation: 1313

How to call function of directive from controller

My directive code is:

(function() {
  angular.module('app')
  .directive('dynamicImage', dynamicImage);

  function dynamicImage($timeout) {
    return {
        restrict: 'A',
        scope: { dynamic:'&dynamicImage' },
        link: function (scope, elem) {
          scope.dynamic = function(){
          //code here
          }
        }
    };
}
})();

My Controller code is : In controller How can I call??

function theMethodToBeCalled() { 
      $scope.dynamic();
}

My HTML:

<div class="col-xs-12" dynamic-image="theMethodToBeCalled">
    <div class="meet_details_status_img" data-ng-repeat="user in meet.user" data-ng-if="user.extra.invitationStatus === 'pending'">
          <img class="img-circle my-meets-status-img"  ng-src="{{ user.displayPicture ? (imageURL + user.id) : 'assets/images/user_thumb.jpg' }}"
          />
     </div>
</div>

Please Help me.

Thanks

Upvotes: 0

Views: 54

Answers (1)

ngLover
ngLover

Reputation: 4578

You can expose an object from controller to directive and can define a method inside that object in the directive. Since you've access to the object which is exposed in directive so you can call any method defined in that directive.

Example -

(function() {
  angular.module('app')
  .directive('dynamicImage', dynamicImage);

  function dynamicImage($timeout) {
    return {
        restrict: 'A',
        scope: { dynamic:'&dynamicImage',methodList:'=' },
        link: function (scope, elem) {
          scope.methodList.dynamic = function(){
          //code here
          }
        }
    };
}
})();

In controller -

function CtrlFun($scope){
   $scope.methodList = {};
   $scope.callDirectiveMethod = function(){
      $scope.methodList.dynamic();
   }
}

HTML

<div dynamic-image method-list="methodList"> </div>

Upvotes: 1

Related Questions