【问题标题】:Rebinding this on angular callback from inside link funtion从内部链接函数重新绑定角度回调
【发布时间】:2016-08-05 20:28:12
【问题描述】:

我有一个类似这样的指令:

app.directive('example', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {
      callback: '&'
    },
    template: '<span ng-click="example.callback()">Click Me</span>',
    bindToController: true,
    controllerAs: 'example',
    controller: function() {
      this.counter = 0;

      this.incrementCount = function() {
        this.counter++;
      };

      this.getCount = function() {
        return this.counter;
      };
    },
    link: function(scope, el, attrs, ctrl) {
      var oldCallback = scope.callback;
      ctrl.callback = function() {
        console.log(ctrl);
        return oldCallback.call(ctrl); // I want to be able to use `this` as the controller to access the API from within the callback
      };
    }
  };
});

使用控制器

app.controller("ctrl", ["$scope", function(s) {
  s.callback = function() {
    this.incrementCount();
    console.log("Value: " + this.getCount());
  };
}]);

然后查看

<div ng-app="app">
  <div class="container" ng-controller="ctrl">
    <example callback="callback()"></example>
  </div>
</div>

(codepen)

当我在链接函数的 ctrl.callback 中登录 ctrl 时,它会按我的预期记录示例控制器,但是当调用 oldCallback 时,它不会按我的意愿将 ctrl 反弹到 this。有什么方法可以从作用域的回调中访问指令控制器中定义的 API,同时仍然为指令使用隔离作用域?

【问题讨论】:

  • 为什么要使用链接功能?您应该能够将 $scope 传递到控制器并从那里访问 $scope.callback。
  • 在实际指令中,我使用链接来装饰回调以返回 true,除非它出于流量控制的目的显式返回 false。

标签: angularjs angularjs-directive


【解决方案1】:

您可以通过回调将指令控制器传递出去。例如

示例 html

<span ng-click="example.callback({$exampleCtrl:example})">Click Me</span>

索引html

<example callback="callback($exampleCtrl)"></example>

控制器

$scope.callback = function($exampleCtrl) {
    $exampleCtrl.incrementCount();
    console.log("Value: " + $exampleCtrl.getCount());
};

http://codepen.io/anon/pen/BzqqzV

另请注意,bindToController 仅在 AngularJs 1.3+ 中受支持,并且您的代码笔使用的是 1.2

【讨论】:

  • 太好了,这正是我需要的。我最初尝试通过模板传递参数,但我想我的语法错误。
  • 是的,这个语法有点奇怪。但它有效
猜你喜欢
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 2019-05-24
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多