Angularjs ng-click指令内部。 ControllerAs连接问题

时间:2016-05-19 12:59:28

标签: javascript angularjs angularjs-directive

单击指令时

ShowPopover不起作用。你能帮我找出问题的原因吗?

指令:

 angular.module('landingBuilder').directive('popoverDirective', popoverDirective);

        function popoverDirective() {
            return {
                restrict: 'E',
                templateUrl: '/libs/landing-builder/directive/popover-directive/popover-directive.html',
                controller: controller,
                controllerAs: 'vm',
                transclude: true,
                bindToController: true
            };

            function controller($element, $document){
                var vm = this;
                vm.showPopover = showPopover();
                function showPopover() {
                    console.log('show popover');
                };
            }
        }

模板:

<div class="input-layover popup-target" ng-click="vm.showPopover"</div>

2 个答案:

答案 0 :(得分:2)

在此使用showPopover()代替showPopover

myApp.directive('myDirective', function() {
  return {
    restrict: 'E',
    template: '<button ng-click=vm.showPopover()>hello</button>',
    controller: controller,
    controllerAs: 'vm',
    transclude: true,
    bindToController: true
  };

  function controller($element, $document) {
    var vm = this;
    vm.showPopover = showPopover;

    function showPopover() {
      console.log('show popover');
    };
  }
});

Working Fiddle

答案 1 :(得分:1)

看看这个小提琴:https://jsfiddle.net/ns0pe1ur/

你在代码中犯了一些错误:

  1. 这不合适html
  2. 您需要在ng-click上调用函数,而不是在控制器内部调用
  3. 您的模板应如下所示:

     <div class="input-layover popup-target" ng-click="vm.showPopover()"></div>
    

    你的控制器是这样的:

      function controller($element, $document) {
        var vm = this;
        vm.showPopover = showPopover;
    
        function showPopover() {
          console.log('show popover');
        };
      }