2

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.

4

3 回答 3

2

问题是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请阅读此答案

于 2016-02-26T09:01:36.437 回答
0

将“this”替换为 vm(View-Model)将解决您的问题。不污染 $scope 对象是一件很时髦的事情。是一个全局上下文,它的值取决于函数调用。

所以,在你的控制器中分配,

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>
于 2016-02-26T09:47:58.327 回答
0

将您的变量添加到$scope而不是this像:

$scope.customers = {};

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

编辑:两种方法都有效。请参阅这篇文章以获得深入的解释。

于 2016-02-26T09:03:42.737 回答