使用$ scope时,view不显示数组数据

时间:2015-03-29 20:31:43

标签: angularjs

我有以下代码片段在我的视图中不起作用:

  myapp.controller('AddChoreController', ['$scope', function ($scope) {
      var choreList = this;
      $scope.choreList.chore = [{ name: 'Gun Running', frequency: 'As Needed', allowance: '$1000', id: 0 },
                                { name: 'Party Planning', frequency: 'Wednesdays', allowance: 'Free', id:1}];

当我从choreList.chore取出$ scope时,我的视图会正确显示数据。

我的观点只是这样做:

                        <tr ng-repeat="chore in chores.chore">
                            <td>{{chore.name}}</td>
                            <td>{{chore.frequency}}</td>
                            <td>{{chore.allowance}}</td>
                        </tr>

我希望数组稍后在屏幕上可用,并在添加新条目时自动加载。

正如您所知,我对angularjs仍然很陌​​生,因此非常感谢任何建议(包含教程链接)。

2 个答案:

答案 0 :(得分:2)

你在这里混合技术。您正在使用Controller As Syntax,它是$scope的替代方法。使用Controller As时,控制器对象本身在$scope上显示为属性,允许您将项目隐式添加到$scope作为控制器的属性而不是作为对象他们自己。在这种情况下,控制器根本不需要引用$scope

您的控制器代码可以简化为:

myapp.controller('AddChoreController', function () {
    var choreList = this;
    choreList.chore = [{ name: 'Gun Running', frequency: 'As Needed', allowance: '$1000', id: 0 },
                       { name: 'Party Planning', frequency: 'Wednesdays', allowance: 'Free', id:1}];
...

此处的chore数组将是控制器的属性,并且可以通过chores.chore直接从视图引用

基于此方法处理属性和范围,重命名属性可能有意义。我可能会这样做:

myapp.controller('AddChoreController', function () {
    var chores = this;
    chores.choreList = [{ name: 'Gun Running', frequency: 'As Needed', allowance: '$1000', id: 0 },
                       { name: 'Party Planning', frequency: 'Wednesdays', allowance: 'Free', id:1}];
...

然后,在您看来:

<div ng-controller='AddChoreController as chores'>
    <tr ng-repeat="chore in chores.choreList">
     ....
</div>

这更清楚地表达了元素的多元化。

答案 1 :(得分:0)

  1. 在控制器中尝试将列表命名为choreList并将其附加到范围:
  2. $scope.choreList= [{ name: 'Gun Running', frequency: 'As Needed', allowance: '$1000', id: 0 }, { name: 'Party Planning', frequency: 'Wednesdays', allowance: 'Free', id:1}];
    
    1. 在视图中,ngRepeat指令遍历数组(附加到范围)

      ng-repeat="chore in choreList"