【问题标题】:ng-repeat with custom directive throwing errorng-repeat 自定义指令抛出错误
【发布时间】:2014-09-22 15:23:18
【问题描述】:

我正在控制器中创建一个自定义指令并在 ng-repeat 中调用它,如下所示:

HTML:

<div ng-controller="TestCtrl">
  <div ng-repeat="page in pages">
   <custom 
    load-data="loadData = fn">
   </custom>
  </div>
</div>  

JS:
测试指令如下:

scope: {
   loadData: "&"
}
controller: ['$scope', '$element', '$timeout', '$filter', function ($scope, $element, $timeout, $filter) {
$scope.loadData({ fn: function(data) {  
 //Data calc.
}});
}  

我从 TestCtrl 调用 loadData 如下:

App.controller('TestCtrl', function($scope, $http, $timeout, $rootScope) {
 $scope.loadData(data);
}  

在 TestCtrl 范围内,如果未使用 ng-repeat 并且工作正常,则存在 loadData 函数,但在使用 ng-repeat 时调用 $scope.loadData(data) 的行处会出现 undefined is not a function 错误。
提前致谢

【问题讨论】:

  • 看起来是范围问题。 ngRepeat 为每个模板实例提供了自己的范围。 link
  • 您可能还想考虑使用 $broadcast 和 $on。 link
  • 我尝试使用$broadcast和$on,同样的问题,如果没有提供ng-repeat,它可以工作,但如果存在ng-repeat,它不会进入$on函数。

标签: javascript angularjs angularjs-directive


【解决方案1】:

你的指令的控制器不正确,它的语法是

 controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }

$timeout, $filter 应该在 $attrs$transculde 之后。即使您不使用它,也需要包含两者

即使经过上述修改,如果仍然存在问题,我们可以进一步检查,但以上必须修复,否则您将无法使用$timeout$filter

【讨论】:

  • 添加了所有字段,但仍然是同样的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 2013-07-23
  • 1970-01-01
相关资源
最近更新 更多