Search code examples
angularjsangular-directiveangular-controller

How to call custom directive in scope function of another controller


I am new to AngularJS. Can anyone tell me with example that how to call a custom directive in a scope function of another controller.

For example I have a controller with a function as follows:

angularApp.controller('sample_Ctrl', function ($scope, $http, $timeout, $rootScope, $location) {
     $scope.showReport = function(id) {
     };
});

I created a customDirective as follows:

var showModalDirective = function ($timeout) {
    return {
        restrict: 'E',
        templateUrl: '/Partials/template1.html',
    };
};
angularApp.directive('showModal', showModalDirective);

So how to call this directive in the showReport function, and how can I pass id to template URL?


Solution

  • You can't call directive in controller. It should be a service.

    Or you can use directive in view:

    Directive:

    var showModalDirective = function ($timeout) {
        return {
            restrict: 'E',
            scope: {
               modalId: '='
            },
            templateUrl: '/Partials/template1.html',
        };
    };
    
    angularApp.directive('showModal', showModalDirective);
    

    Controller:

    angularApp.controller('sample_Ctrl', function ($scope, $http, $timeout, $rootScope, $location) {
    
      $scope.showModal = false;
    
      $scope.showReport = function(id) {
        $scope.showModal = true;
        $scope.modalId = id;
      };
    });
    

    View:

    <div ng-if="showModal">
       <show-modal modal-id="modalId"></show-modal>
    </div>
    

    showModal directive is call when showModal variable is true.