本文介绍了如何将变量中的ng-click可执行操作(&)传递给指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带有指令的HTML视图:

HTML view with directive:

<div click aaa="aaa()" action="action"></div>

控制器:我想在$ scope.action中传递函数bbb():

Controller: I like to pass function bbb() in $scope.action:

app.controller('MainCtrl', function($scope) {
    $scope.aaa = function () { alert('aaa'); }
    $scope.bbb = function () { alert('bbb'); }

    $scope.action = 'bbb()';
});

指令:

app.directive('click', function () {
    return {
        scope: {
            aaa: '&',
            action: '&'
        },
        template: 
            '<button ng-click="aaa()">show aaa (work ok)</button>' +
            '<button ng-click="action">show bbb (not work)</button>' +
            '<br>How to pass ng-click action in variable into directive?'
    }
});

我不知道如何评估将action替换为bbb().

I don't know how to evaluate action to be replaced with bbb().

这里是朋克: http://plnkr.co/edit/d8DtsNARKPPJwk2SO2WJ

推荐答案

$scope.action需要是指向$scope.bbb的指针,而不仅仅是一个松散地引用它的字符串.控制器中的"bbb()毫无意义,而$scope.bbb()是您创建并需要使用的内容.当您使用HTML时,暗含$scope,这就是为什么您只需编写aaa()就可以摆脱困境的原因.

$scope.action needs to be a pointer to $scope.bbb and not just a string that refers to it loosely. "bbb() in the controller means nothing, while $scope.bbb() is what you created and need to use. When you're in HTML, $scope is implied, which is why you can get away with simply writing aaa().

在模板和HTML中,还需要调用action,就像调用aaa一样.

In your template and your HTML, you also need to call action, just as you are calling aaa.

http://jsfiddle.net/DFcJf/

HTML

<div ng-app="app" ng-controller="MainCtrl">
    <div click aaa="aaa()" action="action()"></div>

</div>

JavaScript

JavaScript

var app = angular.module('app', []);

app.directive('click', function () {
    return {
        scope: {
            aaa: '&',
            action: '&'
        },
        template: 
            '<button ng-click="aaa()">show aaa (work ok)</button>' +
            '<button ng-click="action()">show bbb (not work)</button>' +
            '<br>How to pass ng-click action in variable into directive?'
    }
});
app.controller('MainCtrl', function($scope) {
    $scope.aaa = function () { alert('aaa'); }
    $scope.bbb = function () { alert('bbb'); }

    $scope.action = $scope.bbb;
});

这篇关于如何将变量中的ng-click可执行操作(&amp;)传递给指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:21