使用bindToController从指令调用控制器函数

时间:2016-03-28 17:07:36

标签: angularjs

我写了一个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>

2 个答案:

答案 0 :(得分:2)

您有很多问题:

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

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

最后,使用双向绑定而不是&传递函数引用,因为它传递了隐式评估的值。

 bindToController: {
      ctrlFunc: '='
  },

见工作plunkr

答案 1 :(得分:0)

我不确定你需要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>
相关问题