àngularjs指令倒计时

时间:2016-09-19 10:19:29

标签: javascript angularjs

我倒计时效果很好。但我希望为它添加更多功能。

在这种情况下,我想输入一个用于倒计时的字符串(结果将是STRING +倒计时)。

字符串在init-mess中,但我无法理解为什么我无法在指令中检索它。

<countdown init-val="vm.timersteal " init-mess="Du kan utføre enkel krim igjen om" class="ng-isolate-scope"></countdown>
angular
    .module('users')
    .directive('countdown', countdown);

function getFormattedTime(secs) {
    var date = new Date(null);
    date.setSeconds(secs);
    return  date.toISOString().substr(11, 8);
}

function countdown() {
    return {
        restrict: 'E',
        template: '<div class=\"{{class}}\" style=\"float:left; margin-right:5px;\"">{{result}}</div>',
        scope: {
            initVal: '=',
            initmess: '='
        },
        controller: function($scope, $interval) {
            console.log($scope.initVal);
            console.log($scope.initmess);
            $scope.countdownVal = $scope.initVal;
            $scope.countdownVal = Math.floor($scope.countdownVal / 1000) - Math.floor(Date.now() / 1000);

          var b = getFormattedTime($scope.countdownVal);
            $scope.class = "";
            if ($scope.countdownVal > 0) {
                $scope.result = b;
            } else {
                $scope.class = "blink";

                $scope.result = "00:00:00";
            }


            $interval(function () {
                if ($scope.countdownVal > 0) {
                    $scope.class = "";
                    $scope.countdownVal = $scope.initVal;
                    $scope.countdownVal = ($scope.initVal / 1000) - Math.floor(Date.now() / 1000);
                    $scope.result = getFormattedTime($scope.countdownVal);
                } else {
                    $scope.class = "blink";

                    $scope.result = "00:00:00";
                }
            }, 1000);
        }
    }



};

更新:

现在我明白了:

angular.js:13920 Error: [$parse:lexerr] Lexer Error: Unexpected next character  at columns 10-10 [ø] in expression [Du kan utføre enkel krim igjen om].

如何修复以允许字符串?

1 个答案:

答案 0 :(得分:0)

问题在于:

scope: {
    initVal: '=',
    initmess: '='
},

您使用initmess声明=。因此,Angular正在尝试使用initmess中给出的值初始化双向方式。它试图评估一个角度表达式。但是你给Du kan utføre enkel krim igjen om

我相信你想这样做:

scope: {
    initVal: '=',
    initmess: '@'
},

$compile和指令的文档:https://docs.angularjs.org/api/ng/service/ $ compile