Search code examples
javascriptangularjsangular-directive

How to use controller method in custom directive?


Once value is selected from Select using ng-options user will click on startRecording at that time i want to display progressbar that is working from controller but i want to use that logic in directive controller when user click on startRecording i want to pass value to directive or invoke method startRecording from directive so progressbar can show.

diective.js

angular.module("App").directive('progressBarCustom',function () {
    return {
        restrict: 'E',
        scope:{
            message: "=",
            fileSize: "=",
            fileValue: "="
        },
        templateUrl: '/view/partials/progressbar.html',
        controller: function ($scope) {
            var data = $scope.message;
            $scope.progressBarFlag = false;
    }
});

ctrl.js

$scope.startRecording = function () {
        $scope.progressBarFlag = true;
    }

main.html

<div class="col-md-3">
    <select class="form-control" ng-model="selectedFileSize" ng-options="item as item.value for item in FileSizeOptions" ng-change="onSizeChange()"><option value="">Select</option></select>
</div>
<div class="col-md-2">
    <button type="button" class="btn btn-primary" ng-click="startRecording()">Start Recording</button>
</div>


<progress-bar-custom message="event" fileSize="selectedFileSize.size" fileValue="selectedFileSize.value"></progress-bar-custom>

progressbar.html

<uib-progressbar ng-show="progressBarFlag" type="success" class="progress-striped" max="max" animate="true" value="dynamic"><span>{{downloadPercentage}}%</span></uib-progressbar>

Solution

  • Add a link function to your directive and call scope.$parent() to access the controller that holds methods for the progress bar .

    Example :

    angular.module("App").directive('progressBarCustom',function () {
        return {
            restrict: 'E',
            scope:{
                message: "=",
                fileSize: "=",
                fileValue: "="
            },
            templateUrl: '/view/partials/progressbar.html',
            controller: function ($scope) {
                var data = $scope.message;
                $scope.progressBarFlag = false;
        },
    
        link: function(scope, el, attrs) {
    
                el.bind('click', function(event) {
                    scope.$parent.startRecording();
    
    
                });
            }
    });
    

    Hope this helps