I am trying to populate a list of employee
objects from my controller empctrl
in a template.
Here's the controller:
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();
});
However, this code that I wrote isn't working:
<div ng-repeat="employee in empctrl.employees.allEmployees" class="table_row">
<div class="table_column" style="width:2%">{{ $index + 1 }}</div>
<div class="table_column" style="width:8%">{{ employee.employeeName}}</div>
<!-- 7 more columns -->
</div>
Nothing shows up in the UI.
Instead, if I write $scope.employees
in the controller, it works:
<div ng-repeat="employee in employees.allEmployees" class="table_row">
Since I know how tempting it is to do $scope.<everything>
in the controller, I'm trying to avoid using $scope
as much as possible.
If someone could demonstrate the proper use of $scope
and difference betwee alias.abc
and $scope.abc
(where alias
is an alias of controller), I'll be thankful.
Edit: Exact same question is this: 'this' vs $scope in AngularJS controllers
Thanks for this link, PankajParkar.
The problem is
this
which you are accessing insidepopulateTable
function is notthis
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
For more detail, I'd highly recommend you to readup on this article
If you are confused with
this
vsscope
then do read up on this answer