我在尝试使用 $interval
时遇到错误。
Error: Uncaught ReferenceError: $interval is not defined
Plnkr 中的示例代码:plnkr
谁能帮帮我。谢谢!
var MyApp = angular.module('MyApp', []);
(function() {
var MainController = function($scope, $http, $interval) {
var OnSuccess = function(response) {
$scope.user = response.data;
$http.get($scope.user.repos_url).then(OnLoadRepos, OnError)
};
var OnLoadRepos = function(response) {
$scope.repos = response.data;
};
var OnError = function(response) {
$scope.user = "";
$scope.error = "could not fetch the data.";
};
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username).then(OnSuccess, OnError);
};
$scope.message = "GitHub Viewer!";
$scope.username = "angular";
$scope.countdown = 5;
$scope.repoSortOrder = "-stargazers_count";
};
var decrementCountDown = function() {
$scope.countdown -= 1;
if ($scope.countdown < -1) {
$scope.search($scope.username);
}
};
MyApp.controller('MainController', MainController);
var startCountdown = function() {
$interval(decrementCountDown, 1000,$scope.countdown);
};
startCountdown();
}());
最佳答案
错误:
这里你的startCountdown
函数在angular的 Controller 之外
所以它是简单的 javascript 函数。
在 Javascript 函数中,您正在使用 $interval
依赖项,因此它不会工作。
解决方案:
您在 Controller 中注入(inject)了 $interval
的另一件事,因此通过将您的 startCountdown
函数转移到 Controller 中的 Angular 函数中将起作用。
var MyApp = angular.module('MyApp', []);
(function() {
var MainController = function($scope, $http, $interval) {
var OnSuccess = function(response) {
$scope.user = response.data;
$http.get($scope.user.repos_url).then(OnLoadRepos, OnError)
};
var OnLoadRepos = function(response) {
$scope.repos = response.data;
};
var OnError = function(response) {
$scope.user = "";
$scope.error = "could not fetch the data.";
};
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username).then(OnSuccess, OnError);
};
$scope.message = "GitHub Viewer!";
$scope.username = "angular";
$scope.countdown = 5;
$scope.repoSortOrder = "-stargazers_count";
};
var decrementCountDown = function() {
$scope.countdown -= 1;
if ($scope.countdown < -1) {
$scope.search($scope.username);
}
$scope.startCountdown = function() {
$interval(decrementCountDown, 1000,$scope.countdown);
};
$scope.startCountdown();
};
MyApp.controller('MainController', MainController);
}());
关于angularjs - Angular : $interval undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29788769/