从ngClick调用父指令函数

时间:2015-08-05 21:20:38

标签: angularjs angularjs-directive angularjs-scope

考虑以下指令:(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

谢谢!

3 个答案:

答案 0 :(得分:2)

嗯,最简单的方法是将内部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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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