В приведенном ниже коде,
<!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}}
экземпляру экземпляра {{o.time}}
$interval
?
Измените код в этом формате
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);
Надеюсь это поможет