AngularJS - $ interval内置服务

时间:2016-03-25 11:58:41

标签: angularjs

在下面的代码中,

<!DOCTYPE html>
<html ng-app="app14" ng-cloak>
    <head>
        <meta charset="UTF-8">
        <title> Angular built-in services</title>
        <style>
            [ng\:cloak], [ng-cloak], .ng-cloak{
                display: none;
            }

        </style>
    </head>
    <body>
        <div ng-controller="mainCtrl as o">

            <!-- Using $interval service-->
            Current time: {{o.time}}

        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-sanitize.js"></script>
        <script type="text/javascript" src="js/exam14.js"></script>
    </body>
</html>
var app14 = angular.module('app14', ['ngSanitize']);

function MainController($window, $location, $interval, $log, $exceptionHandler, $sanitize){
    /****************interval service*******/
    $interval(function(){
        var hour = new Date().getHours();
        var minutes = ('0' + new Date().getMinutes()).slice(-2);
        var seconds = ('0' + new Date().getSeconds()).slice(-2);

        this.time = hour + ":" + minutes + ":" + seconds; // 'this' refers to window but not to controller instance.

    },2000);
}
app14.controller('mainCtrl', MainController);

在上面的代码中,$interval计算每2秒的时间。

this.time显然是指window回拨中的$interval个对象。

$scope中注入MainController解决了问题,但控制器正在使用this关键字来引用控制器实例。

如何在{{o.time}}回调中访问$interval实例成员?

1 个答案:

答案 0 :(得分:2)

将您的代码更改为此格式

var app14 = angular.module('app14', ['ngSanitize']);

function MainController($window, $location, $interval, $log, $exceptionHandler, $sanitize){
    /****************interval service*******/
    var self = this;   //you create a variable and pass the controller object into it

    $interval(function(){
        var hour = new Date().getHours();
        var minutes = ('0' + new Date().getMinutes()).slice(-2);
        var seconds = ('0' + new Date().getSeconds()).slice(-2);

        self.time = hour + ":" + minutes + ":" + seconds; // use self rather than this. Because self points to the controller object now. 

    },2000);
}
app14.controller('mainCtrl', MainController);

希望这有帮助