Search code examples
javascriptangularjsangular-directive

How to invoke $scope function from angularjs directive?


I know angularjs but this is first time i am writing angular directive so i am trying to create directive for progressbar everytime i receive message in controller based on that i am calculating string size and converting into bytes for progressbar.Problem with below code i see error $scope.random is not a function. Any idea what is implemented wrong ?

directive.js

angular.module("App").directive('progressBarCustom', function() {
    return {
        restrict: 'E',
        scope: {
            message: "="
        },
        templateUrl: '/view/partials/progressbar.html',
        controller: function($scope) {
            var data = $scope.message;
            var currentFileBytes = [];
            var currentBytesSum;
            $scope.maxBytes = 3000;
            getByteLen(data);
            $scope.random = function(value) {
                $scope.dynamic = value;
                $scope.downloadPercentage = parseFloat((value / $scope.maxBytes) * 100).toFixed(0);
                console.log('current value-dynamic', $scope.dynamic);
            };

            function getByteLen(normal_val) {
                // Force string type
                normal_val = String(normal_val);
                currentFileBytes.push(byteLen);
                currentBytesSum = currentFileBytes.reduce(function(a, b) {
                    return a + b;
                }, 0);
                $scope.random(currentBytesSum);
                formatBytes(currentBytesSum);
                return byteLen;
            }

            function formatBytes(bytes, decimals) {
                var data = parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
                console.log('sum of all the bytes', data);
                $scope.currentBytes = data;
            }
        }
    }
});

progressbar.html

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

main.html

<progress-bar-custom message="event"></progress-bar-custom>

controller.js

$scope.event = ["lorem ipsum","lorem ipsum"];

Solution

  • You are calling getByteLen before $scope.random is assigned.

    Use this instead:

            $scope.random = function(value) {
                $scope.dynamic = value;
                $scope.downloadPercentage = parseFloat((value / $scope.maxBytes) * 100).toFixed(0);
                console.log('current value-dynamic', $scope.dynamic);
            };
            getByteLen(data);