AngularJS:在迭代对象时代码无法运行。
AngularJS:在迭代对象时代码无法运行。
这个问题已经有答案了:
我正在尝试从我的控制器empctrl
中在模板中填充一个employee
对象列表。
这是控制器:
app.controller('employeeController', function ($scope, employeeService) { this.employees = {}; this.populateTable = function (data) { this.employees = data; }; var error = function (err) { console.log("Error: " + err); }; // Call Service to List all Employees console.log("Service called to populate table."); employeeService.output().then(this.populateTable, error); this.populateTable(); });
然而,我编写的这段代码不起作用:
{{ $index + 1 }} {{ employee.employeeName}}
UI中没有显示任何内容。
相反,如果我在控制器中写 $scope.employees
,它就可以正常工作:
由于我知道在控制器中使用$scope.
是多么具有诱惑性,所以我试图尽可能地避免使用$scope
。
如果有人能演示正确使用$scope
和别名alias.abc
与$scope.abc
的区别(其中alias
是控制器别名),我将不胜感激。
编辑:确切的问题是:\'this\' vs $scope in AngularJS controllers
感谢这个链接,PankajParkar。
admin 更改状态以发布 2023年5月23日
把你的变量添加到$scope
中,而不是像this
一样:
$scope.customers = {}; $scope.populateTable = function (data) { $scope.employees = data; };
编辑:两种方法都可以。请参阅此文章以获取深入解释。
问题是你在populateTable
函数内部访问的this
不是你在控制器函数中拥有的那个this
。
最好将this
变量存储在某个变量中,以确保你正在引用正确的对象。
控制器
app.controller('employeeController', function ($scope, employeeService) { var vm = this; vm.employees = {}; vm.populateTable = function (data) { vm.employees = data; }; var error = function (err) { console.log("Error: " + err); }; // Call Service to List all Employees console.log("Service called to populate table."); employeeService.output().then(vm.populateTable, error); vm.populateTable(); });
更多细节,请阅读this article
如果你对this
vs scope
感到困惑,请阅读this answer