Angular $scope 函数在 ng-repeat 外部无法正常工作

3
我有一个table元素,在其中声明了一个控制器(目前应用程序中仅有一个)。我还在tbody元素中的tr上使用了ng-repeat,这个功能很好地工作着,按预期创建了多个表格行。在控制器中,我有一些针对单个表格行的api调用,这些调用正常工作,还有一个从thead中的th中调用的函数,但我无法让它起作用。我知道这是一个作用域问题,但我就是不明白我做错了什么。
简化后的html片段:
<table ng-controller='myController'>
    <thead>
         <tr>
             <th>Username</th>
             <th><button ng-click='doStuff()'>Do stuff</button></th>
         </tr>
    </thead>
    <tbody>
         <tr ng-repeat='user in users'>
             <td>{{user.name}}</td>
             <td><button ng-click='delete(user)'>Delete</button>
         </tr>
    </tbody>
</table>

JavaScript简化代码片段:

app.controller('myController', ['$scope', '$http', users, function($scope, $http, users) {
    //api call to get users, working fine
    users.getAll().success(function(data) {
        $scope.users = data;
    });

    //api call to delete users, also working fine
    $scope.delete = function(user) {
        users.delete(user).success(function() {});
    };

    //can't get this to fire
    $scope.doStuff = function() {
        alert('I do stuff');
    };
}]);

任何见解都将有所帮助,提前感谢!
编辑:我猜问题可能来自其中一个模块,因此我将整个内容复制到了 plnkr 中。对于样式的影响表示抱歉,为了更简单的代码,已将其删除。
编辑2:通过研究 plnkr,我发现在 thead 中有一个未关闭的 div 元素。很遗憾,感谢您的回复,请原谅我的粗心大意。
编辑3:甚至更仔细的研究表明,问题实际上也存在于设计不良的 jasmine 单元测试中。

1
你发布的代码很好(除了users应该加引号)。当按钮被点击时,doStuff()将被调用。我会尝试在jsFiddle中重现你的问题。 - rob
请检查更新后的问题。 - Piotr Jaworski
1个回答

1

它似乎正在触发。我不得不模拟异步加载users,但这不应该有任何影响。你能添加一个片段来演示这个问题吗?

 angular.module('app', []).controller('myController', ['$scope', '$http', '$timeout',
   function($scope, $http, $timeout) {
     //api call to get users, working fine

     $timeout(function() {
       $scope.users = [{
         name: 'A'
       }, {
         name: 'B'
       }];
     }, 1000);

     //api call to delete users, also working fine
     $scope.delete = function(user) {
       console.log('delete', user);
     };


     $scope.doStuff = function() {
       console.log('I do stuff');
     };
   }
 ]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>

<div ng-app="app">

  <table ng-controller='myController'>
    <thead>
      <tr>
        <th>Username</th>
        <th>
          <button ng-click='doStuff()'>Do stuff</button>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat='user in users'>
        <td>{{user.name}}</td>
        <td>
          <button ng-click='delete(user)'>Delete</button>
      </tr>
    </tbody>
  </table>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接