AngularJS: code does not work when iterating through an object

I am trying to populate a list of objects employeefrom my controller empctrlin a template.

Here is 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 I wrote does not work:

<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 is displayed in the user interface.
Instead, if I write $scope.employeesin the controller, it works:

<div ng-repeat="employee in employees.allEmployees" class="table_row">

Since I know how tempting it is to do this $scope.<everything>in the controller, I try to avoid using $scopeas much as possible.


If someone can demonstrate the proper use $scopeand difference of betwee alias.abcand $scope.abc(where aliasis the controller alias), I will be grateful.

: : 'this' vs $scope AngularJS

, PankajParkar.

+1
3

this, populateTable, 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 vs scope,

+2

$scope this, :

$scope.customers = {};

$scope.populateTable = function (data) {
    $scope.employees = data;
};

: . . .

0

"this" vm (View-Model) . $scope - groovy. - , .

,

var vm = this;
  vm.empTable = function (data) {
  vm.employeeList = data.data; 
};

.. vm . .

,

<div ng-controller="MainCtrl as main">
    <div ng-repeat=" employee in main.vm.employeeList ">
        {{employee.name}}
    </div>
</div>
0

All Articles