AngularJS: code not working when iterating through object
This question already has an answer here:
The problem is this
which you are accessing inside populateTable
function is not this
which you have there in your controller function.
Better do keep this
variable inside some variable, so that by having it you will make sure you are referring to correct object.
Controller
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();
});
For more detail, I'd highly recommend you to readup on this article
If you are confused with this
vs scope
then do read up on this answer
Add your variables to the $scope
instead of this
like:
$scope.customers = {};
$scope.populateTable = function (data) {
$scope.employees = data;
};
Edit: both methods work. See this article for a in depth explanation.
Substituting "this" to vm (View-Model) will solve your issue. Not polluting $scope object is a groovy thing. this is a global context and its value depends on a function call.
So, in your controller just assign,
var vm = this;
vm.empTable = function (data) {
vm.employeeList = data.data;
};
..and use the vm object elsewhere in your controller. It will be useful to keep the code clean while working with multiple controllers in a view.
Don't forget to give an alias name to the controller,
<div ng-controller="MainCtrl as main">
<div ng-repeat=" employee in main.vm.employeeList ">
{{employee.name}}
</div>
</div>
链接地址: http://www.djcxy.com/p/77800.html
上一篇: 在控制器中使用$ scope和this有什么区别?
下一篇: AngularJS:迭代对象时代码不工作