AngularJS控制器中$timeout函数注入位置及未定义问题咨询
Hey there, let's fix that $timeout undefined issue for you! The problem lies with your dependency injection setup—you're using AngularJS's array-style injection, but forgot to add $timeout to the injection list, which is why Angular can't resolve the dependency.
正确的修改方式
You need to add "$timeout" to the array of dependencies when registering your controller, and make sure its order matches the parameters in your controller function exactly. Here's the corrected code:
(function () { "use strict"; angular .module("taskManagement") // Add "$timeout" to the injection array here .controller("TaskListCtrl", ["taskResource", "$timeout", TaskListCtrl]); function TaskListCtrl(taskResource, $timeout) { var vm = this; taskResource.query(function (data) { vm.tasks = data; }); vm.updateStatus = function (task) { debugger; task.status = task.status; // Now you can use $timeout normally, like this: // $timeout(function() { // // Your delayed logic here // }, 1000); }; } })();
为什么这能解决问题?
AngularJS's array-style injection exists to prevent dependency name loss during code minification. When you minify your code, parameter names like $timeout get renamed to short variables (e.g., a), but the string values in the array stay intact. Angular uses these strings to look up the correct services to inject.
The strings in the array must match the order of the function parameters exactly: the first string maps to the first parameter, the second to the second, and so on. Since you only included "taskResource" before, Angular had no idea to inject the $timeout service into your controller, hence the undefined error.
另一种可选的注入方式
If you prefer a cleaner look, you can also use the $inject property to declare dependencies instead—this works the same way:
(function () { "use strict"; angular .module("taskManagement") .controller("TaskListCtrl", TaskListCtrl); // Declare dependencies with $inject TaskListCtrl.$inject = ["taskResource", "$timeout"]; function TaskListCtrl(taskResource, $timeout) { // Your controller logic stays the same } })();
Either method will fix your issue—pick whichever style you find more readable!
内容的提问来源于stack exchange,提问作者Rod

