Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    })
like image 982
Spring Avatar asked Aug 06 '13 11:08

Spring


2 Answers

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

like image 129
Ivan Chernykh Avatar answered Oct 18 '22 23:10

Ivan Chernykh


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.

like image 3
Blackhole Avatar answered Oct 18 '22 22:10

Blackhole