How to pass ng-click executable action (&) in variable into directive?

浪子不回头ぞ 提交于 2019-12-10 10:08:24

问题


HTML view with directive:

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

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()';
});

Directive:

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?'
    }
});

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

here is plunker: http://plnkr.co/edit/d8DtsNARKPPJwk2SO2WJ


回答1:


$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().

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

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;
});


来源:https://stackoverflow.com/questions/16234766/how-to-pass-ng-click-executable-action-in-variable-into-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!