【问题标题】:How to get isolated scope of a directive with ngrepeat and two way bind?如何使用 ngrepeat 和两种方式绑定获得指令的隔离范围?
【发布时间】:2015-06-15 19:45:04
【问题描述】:

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

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

当我在 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 中的完整代码

【问题讨论】:

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


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 2016-07-01
      • 2017-05-11
      • 1970-01-01
      • 2014-07-11
      相关资源
      最近更新 更多