AngularJS: code not working when iterating through object [duplicate]

冷暖自知 提交于 2019-11-29 17:15:28
Pankaj Parkar

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!