javascript - 如何使用 ngrepeat 和双向绑定(bind)获取指令的隔离范围?

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

当从 Controller (父级)调用链接函数时,我们如何获得指令的特定隔离范围?

我有一个指令并使用 ng-repeat 重复它。每当单击指令模板中的按钮时,它将调用指令 Controller 中的函数 Stop(),该函数又调用父 Controller 中的函数 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 中的完整代码

最佳答案

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

HTML:

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

Controller :

$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

关于javascript - 如何使用 ngrepeat 和双向绑定(bind)获取指令的隔离范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29555509/

相关文章:

javascript - 预选一个值

javascript - 当我有嵌套指令时,如何访问特定的父作用域?

javascript - 兄弟 Controller 可以在没有父级帮助的情况下相互通信吗 - AngularJS

javascript - Angular Directive(指令)编译器触发 ng-click 两次

javascript - 如何在 React Native 中编写深度链接

javascript - 如果使用 javascript 选中其他复选框,如何选中一个复选框?

angularjs - 如何从指令模板访问Object.keys(object).length?

javascript - 如何在 ES6 中注入(inject)指令 Controller

javascript - Google map - 默认图钉仍然显示并遮盖自定义图标

javascript - AngularJS:使用过滤器将数组拆分为数组