如何从angularjs指令调用$ scope函数?

时间:2016-08-25 14:03:33

标签: javascript angularjs angular-directive

我知道angularjs,但这是我第一次写angular指令所以我每次在控制器中收到消息时都会尝试为progressbar创建指令,因为我正在计算字符串大小并转换为progressbar.Problem的字节,代码如下我看到错误$scope.random不是一个函数。知道什么是错误的吗?

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"];

1 个答案:

答案 0 :(得分:1)

您在分配getByteLen之前致电$scope.random

请改用:

        $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);