简体   繁体   中英

AngularJS bind clicking instead of ng-click

I was looking at AngularJs and have a question, this is my directive:

myApp.directive("enter", function(){
return{
    restrict: 'A',
    scope:{},
    controller: function($scope){
        $scope.logSomething=function(somevalue){
            console.log(somevalue+" is logged");
        }
    },
    template: '<input type="text" ng-model="myModel">'+
              '<div ng-click="logSomething(myModel)">click me</div>'
}
})

This works, but my question is how can I do the same thing using bind clicking instead of ng-click directive? Not that it is better(maybe?), but for curiosity

it should be including something like this but couldn't get the big picture:

 function(scope, element, attrs){
    element.bind("click", function(){
        scope.$apply(attrs.enter);
    })

Try this one:

myApp.directive("enter", function(){
  return{
    restrict: 'A',
    scope:{},
    controller: function($scope){
        $scope.logSomething=function(somevalue){
            console.log(somevalue+" is logged");
        }
    },
    template: '<input type="text" ng-model="myModel">'+
              '<div button>click me</div>'
}
});

myApp.directive("button", function(){   
  return{
    restrict: 'A',
    link: function(scope , element){
       element.bind("click", function(e){
          scope.logSomething( scope.myModel );
       });
    }
}
});

Plunk: http://plnkr.co/edit/RCcrs5?p=preview

As you pointed out, you can simply use element.bind :

myApp.directive(
    'clickMe',
    function () {
        return {
            template : '<div>Click me !</div>',
            replace : true,
            link : function (scope, element) {
                element.bind('click', function ()
                {
                    alert('Clicked !');
                });
            },
        };
    }
);

Fiddle

But of course, in your case, you must use ngClick instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM