如何使用ng repeat和双向绑定获取指令的隔离范围?

时间:2015-04-10 07:16:13

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-controller

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

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

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

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

找到pluker 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中的完整代码

1 个答案:

答案 0 :(得分:1)

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

<强> 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