如何在指令中定义两个ng-click函数

How to define two ng-click functions in a directive?

本文关键字:两个 ng-click 函数 指令 定义      更新时间:2023-09-26

这是我在模板中的代码。

    <button ng-click="{{backFunction}}" ng-show="{{backShow}}"> Back </button>
    <button ng-click="{{nextFunction}}" ng-show="{{nextShow}}"> Next </button>

指令代码
directive('navigationButtons', function() {
    return {
        restrict: 'AE',
        templateUrl : 'angular/app/partials/navigationButtons.html',
        scope: {
            backFunction: '@',
            backShow: '@',
            nextFunction: '@',
            nextShow: '@'
        }
        };
})

查看代码(我使用的指令)

<navigation-buttons nextFunction="a.active=true" nextShow="true" backFunction="b.active=false" backShow="true"></navigation-buttons>

显示错误为Syntax Error: Token 'nextFunction' is unexpected

你应该接收带有&而不是@

也接受布尔值显示/隐藏与=如果你需要双向绑定&不想设置$watch/$observe

directive('navigationButtons', function() {
    return {
        restrict: 'AE',
        templateUrl : 'angular/app/partials/navigationButtons.html',
        scope: {
            backFunction: '&',
            backShow: '=',
            nextFunction: '&',
            nextShow: '='
        }
        };
})

把函数传递给指令

编辑

还可以查看这篇关于指令的好文章

你的代码中有一些错误,首先,在你的模板中,你改变了驼峰大小写为破折号分隔,并删除了花括号

<button ng-click="backFunction()" ng-show="backShow"> Back </button>
<button ng-click="nextFunction()" ng-show="nextShow"> Next </button>

现在在指令中替换作用域隔离:

directive('navigationButtons', function() {
return {
    restrict: 'AE',
    templateUrl : 'angular/app/partials/navigationButtons.html',
    scope: {
        backFunction: '&',
        backShow: '@',
        nextFunction: '&',
        nextShow: '@'
    }
};

我创建了一个jsfiddle与您的代码工作:http://jsfiddle.net/v7V6y/

最好!