将函数传递给ng-repeat对象

时间:2016-07-25 13:01:50

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

所以我的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创建默认范围并且我可以访问所有想要的属性时,我无法使用父函数。

1 个答案:

答案 0 :(得分:0)

这是我对你挑战的解决方案:
在视图中:

<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

相关问题