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

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

本文关键字:指令 隔离 范围 绑定 ngrepeat 何使用      更新时间:2023-09-26

在从控制器(父级)调用链接函数时,如何获得指令的特定隔离范围?

我有一个指令,并用ng重复它。每当单击指令模板中的按钮时,它都会调用指令控制器中的函数-Stop(),该函数反过来调用父控制器中的功能test(),在test()中,它会调用指令链接函数中的方法dirSample()。

当我在dirSample()中打印作用域时,它会打印上一个创建的指令的作用域,而不是调用它的指令。

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

在这里找到plucker

.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