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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With