Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

ng-click attribute on angularjs directive

I think it should be easy to use the well known angular attributes on a directive out of the box.

For example if the name of my directive is myDirective I would like to use it this way:

<div ng-controller="myController">
   <my-directive ng-click="doSomething()"><my-directive>
</div>

instead of needing to define a custom click attribute (onClick) as in the example below

<div ng-controller="myController">
   <my-directive on-click="doSomething()"><my-directive>
</div>

It seems that ng-click can work, but then you need to specify ng-controller on the directive tag too which I don't want. I want to define the controller on a surrounding div

Is it possible to use ng-click on a directive together with a controller defined on a parent html element?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is updated code. Maybe is this what you were looking for.

Html:

<div data-ng-app="myApp">
    <div data-ng-controller="MyController">
        <my-directive data-ng-click="myFirstFunction('Hallo')"></my-directive>
        <my-directive data-ng-click="mySecondFunction('Hi')"></my-directive>
    </div>
</div>

Angular:

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

app.directive('myDirective', function(){
    return {
        restrict: 'EA',
        replace: true,
        scope: {
            eventHandler: '&ngClick'
        },
        template: '<div id="holder"><button data-ng-click="eventHandler()">Call own function</button></div>'
    };
});

app.controller('MyController', ['$scope', function($scope) {
    $scope.myFirstFunction = function(msg) {
         alert(msg + '!!! first function call!');   
    };
    $scope.mySecondFunction = function(msg) {
         alert(msg + '!!! second function call!');   
    };
}]);

Edit

Check solution that I made in jsFiddler is that what you were looking for?

http://jsfiddle.net/migontech/3QRDt/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...