【问题标题】:Passing function into ng-repeat object将函数传递给 ng-repeat 对象
【发布时间】:2016-11-28 20:11:41
【问题描述】:

所以我对 ng-repeat 指令有疑问。在我的代码中,我有一个父控制器,它的数据存储为对象数组。

$scope.queue = [
  {
    name: 'Mark',
    sex: 'Male',
    age: 21
  },
  {...}
];

$scope.changePositionInQueue = function (currIndex, targetIndex) {
  // move up / down person in queue 
};

我想要做的是将父控制器的功能传递给我的指令的('person')隔离范围,同时能够使用'$index'、'$first'、'$last'变量。

<person data-change-position="changePositionInQueue" data-person="person" ng-repeat="person in queue"></person>

指令范围声明:

scope: {
 person: '=',
 changePosition: '&'
}

问题是当我在 ng-repeat 循环中创建隔离范围时,我会丢失 ng-repeat 属性。另一方面,当我通过 ng-repeat 创建默认范围并且我可以访问所有想要的属性时,我无法使用父函数。

【问题讨论】:

  • 所以甚至将作用域上的那些作为参数传递给您的隔离作用域指令
  • 感谢您的回答,但我该怎么做呢?将参数作为 person.$index 或 $index 传递给我在指令子范围内的“未定义”。
  • 在你的范围指令定义中类似于index: @,然后在html data-index="$index" 上应该这样做

标签: javascript angularjs angularjs-directive angularjs-scope ng-repeat


【解决方案1】:

这是我对您的挑战的解决方案:
观点:

<my-directive dir-func="fnc($index)" data="data" ng-repeat="data in datas"><span>{{data.id|json}}</span><br></my-directive>

在链接中直接调用父函数:

myApp.directive('myDirective', function() {
  return {
    //require: 'ngModle',
    scope: {
      data: "=",
      dirFunc: "&"
    },
    link: function(scope, elem, attr, ngModel) {
        scope.dirFunc() // parent scope.func is called here where you get the alert

    }

  }

See the Plunker for detail

【讨论】:

  • 感谢您的回答。它没有直接帮助我,因为我通过从 $parent 范围获取 $index 属性来解决这个问题,但是我的功能仍然无法正常工作。通过查看您的指令,我发现了一个错误。我在指令中通过引用传递函数,但没有提供有关它所用参数的信息。问题还是解决了,非常感谢!
  • 很高兴有帮助,示例的目的就是为了这个! :) 干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多