【问题标题】:Call parent directive function from ngClick从 ngClick 调用父指令函数
【发布时间】:2015-08-05 21:20:38
【问题描述】:

考虑以下指令:(Plunker)

.directive('myDirective', function() {
    return {
        scope: {
            opt: '='
        },
        link: function(scope, element, attrs) {
            scope.foo = function() {
                console.log('bar');
            }
        }
    }
});

还有html:

<div my-directive>
    <a ng-click="foo()">Click Me</a>
</div>

单击链接不会触发foo(),可能是因为隔离范围(因为如果我删除它 - 它可以工作)。
我怎样才能使它在一个孤立的范围内工作?

编辑:
内部html是动态的,所以不能用template

谢谢!

【问题讨论】:

  • 如果您的内部 html 始终相同,则应使用包含 Click Me 的模板。现在,您实际上是在父作用域上调用 foo()。
  • 不幸的是,内部 html 并不总是相同的。更新了问题。

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

嗯,最简单的方法是将内部 html 移动到指令的 template 属性中:

        angular
        .module('myApp', [])
        .directive('myDirective', function() {
            return {
                scope: {
                    opt: '=',
                    foo: '&'
                },
                link: function(scope, element, attrs) {
                    scope.foo = function() {
                        console.log('bar');
                    }
                },
                template: '<a ng-click="foo()">Click Me</a>'
            }
        });

还有html:

<div my-directive></div>

http://plnkr.co/edit/ZbL2jVCdHuB4dP4y13fv?p=preview

【讨论】:

    【解决方案2】:

    JS:

    angular
        .module('app', [])
        .directive('myDirective', function() {
            return {
                scope: {
                    opt: '='
                },
                template: function (element, attrs) {
                    return element.html();
                },
                controller: function () {
                    var vm = this;
                    vm.foo = function () {
                        alert('bar!');
                    }
                },
                controllerAs: 'Ctrl'
            }
        });
    

    HTML:

    <div my-directive>
        <a ng-click="Ctrl.foo()">Click Me</a>
    </div>
    

    示例:http://codepen.io/anon/pen/zGegNV

    【讨论】:

      【解决方案3】:

      您可以在指令本身中连接点击事件处理程序:

      angular
          .module('myApp', [])
          .directive('myDirective', function() {
              return {
                  scope: {
                    opt: '='
                  },
                  link: function(scope, element, attrs) {
                      element.on('click', function() {
                        console.log('bar');  
                      })
                  }
              }
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-21
        • 2018-01-03
        • 2017-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-14
        • 1970-01-01
        相关资源
        最近更新 更多