【问题标题】:Calling controller function from directive using bindToController使用 bindToController 从指令调用控制器函数
【发布时间】:2016-03-28 17:07:36
【问题描述】:

我写了一个 plunker 来看看如何使用 bindToDirective 来隔离作用域并使用指令控制器来调用主控制器功能,但是,我做错了。你能推荐一下吗?

这是笨蛋:http://plnkr.co/edit/UJLjTmIiHydHr8qRzAsX?p=preview

代码示例:

.controller('Ctrl', function() {
  var self = this;
  self.func = function() {
    console.log('In the controller function');
  };
})

.directive('myDirective', [ function() {
  var self = {};
  self.link = function (scope, elem, attrs, ctrl) {
      elem.bind('click', function () {
          ctrl.ctrlFunc();
      });
      elem.addClass('fa fa-file-excel-o fa-lg');
  };
  return {
      restrict: 'E',
      scope: {},
      controller: function () {
      },
      controllerAs: 'DirCtrl',
      bindToController: {
          ctrlFunc: '&'
      },
      link: self.link
  };
}])

将主控制器功能与指令关联的html示例:

<div ng-controller="Ctrl">
  <my-directive ctrlfunc="Ctrl.func()"></my-directive>
</div>

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    你有很多问题:

    您的指令参数名称中需要一个连字符,并且您应该传递函数引用,而不是直接调用函数(使用参数):

    <my-directive ctrl-func="ctrl.func"></my-directive>
    

    其次,您在控制器中使用别名语法 (var self = this;),但不在模板中。您需要将其更新为以下内容:

    <div ng-controller="Ctrl as ctrl">
      <my-directive ctrl-func="ctrl.func"></my-directive>
    </div>
    

    最后,使用双向绑定而不是 &amp; 传递函数引用,因为这会传递值以进行隐式评估。

     bindToController: {
          ctrlFunc: '='
      },
    

    查看工作plunkr

    【讨论】:

      【解决方案2】:

      我不确定你是否需要 bindToController...

      这个版本调用你Ctrl的函数:http://plnkr.co/edit/Rxu5ZmmUAU8p63hR2Qge?p=preview

      JS

      angular.module('plunker', [])
      .controller('Ctrl', function($scope) {
        $scope.func = function() {
          console.log('In the controller function');
        };
      })    angular.module('plunker', [])
      
        .controller('Ctrl', function($scope) {
          $scope.func = function() {
            console.log('In the controller function');
          };
        })
      
        .directive('myDirective', [ function() {
          return {
              template: '<pre>[clickme]</pre>',
              replace: true,
              restrict: 'E',
              scope: {
                target: '&'
              },
              link: function (scope, elem, attrs) {
                  elem.bind('click', function () {
                      var fn = scope.target && scope.target(scope);
                      fn && fn();
                  });
                  elem.addClass('fa fa-file-excel-o fa-lg');
              }
          };
        }])
      

      HTML

      <div ng-controller="Ctrl">
        <my-directive target="func"></my-directive>
      </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多