如何使用ngrepeat和双向绑定获得指令的隔离范围?

How to get isolated scope of a directive with ngrepeat and two way bind?

我们如何在从控制器(父)调用 link 函数时获得指令的特定隔离范围?

我有一个指令并使用 ng-repeat 重复它。每当单击指令模板中的按钮时,它将调用指令控制器中的函数 Stop() ,指令控制器又调用父控制器中的函数 test(),在 test() 内部,它将调用指令的 [= 中的方法 dirSample () 24=]函数。

当我在 dirSample() 中打印范围时,它打印的是最后创建的指令的范围,而不是调用它的指令的范围。

如何获取调用它的指令的范围?

找到吸血鬼here

.directive('stopwatch', function() { 
return {
restrict: 'AE',
scope: {
meri : '&',
control: '='
},
templateUrl: 'text.html',
link: function(scope, element, attrs, ctrl) {
scope.internalControl = scope.control || {};
scope.internalControl.dirSample = function(){
console.log(scope)
console.log(element)
console.log(attrs)
console.log(ctrl)
}
},
controllerAs: 'swctrl',
controller: function($scope, $interval) 
{
var self = this;
self.stop = function() 
{
console.log($scope)
$scope.meri(1)
};
}
}});

plunker 中的完整代码

我已将您函数的绑定从 & 更改为 =,因为您需要传递一个参数。这意味着一些语法更改是有序的,如果你想在最后一直拥有它,你还需要沿着链传递范围:

HTML:

<div stopwatch control="dashControl" meri="test"></div>

控制器:

$scope.test = function(scope)
{
   console.log(scope);
   $scope.dashControl.dirSample(scope);
}

指令:

.directive('stopwatch', function() { 

  return {
  restrict: 'AE',
  scope: {
    meri : '=',
    control: '='
  },

  templateUrl: 'text.html',

  link: function(scope, element, attrs, ctrl) {

    scope.internalControl = scope.control || {};
    scope.internalControl.dirSample = function(_scope){
      console.log(_scope);

    }
  },
  controllerAs: 'swctrl',
  controller: function($scope, $interval) 
  {
    var self = this;
    self.stop = function() 
    {
      console.log($scope);
      $scope.meri($scope);
    };
  }
}});

Plunker