Reputation: 34188
i am learning angular. so trying to construct my first directive which interact with DOM but not working. please tell me what i miss in code. here is code.
<div class="main" ng-app="myApp">
<button data-ng-click="submit()" my-directive>click</button>
</div>
app.module('myApp', []);
app.directive('myDirective',function(){
return function(scope, element, attrs){
element.click(function(){
alert('hello');
element.parent().find('.main').append('<div>Some text</div>');
})
}
})
my js fiddle link https://jsfiddle.net/tridip/2fooy06c/
Upvotes: 0
Views: 381
Reputation: 1847
Please change your code as below and it will work. There is no such function as click
in element. Please check this documentation https://docs.angularjs.org/api/ng/function/angular.element here
Also do not forget to include type
and link
attribute in your directive. Type
is used to indicate what kind of directive you are creating. Refer here for more details
app.directive('myDirective',function(){
return {
type: "A",
link: function(scope, element, attrs) {
element.on("click", function() {
alert('hello');
element.parent().append('<div>Some text</div>');
});
}
}
});
refer to this plnkr example https://plnkr.co/edit/CYyOKzjR1kBR3U0tG3jv?p=preview for more details
Upvotes: 1
Reputation: 8375
You need to bind click function. See demo
app.directive('myDirective', function () {
return {
link: function ($scope, element, attrs) {
element.bind('click', function () {
alert('hello');
element.parent().append('<div>Some text</div>');
});
}
};
});
Upvotes: 0
Reputation: 12103
element.click is not a function. you need to attach event using .bind
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective',function(){
return {
link: function(scope, element, attrs){
element.bind('click',function(){
alert('hello');
element.parent().append('<div>Some text</div>');
})
}
}
})
DEMO: http://jsfiddle.net/Lvc0u55v/2018/
Upvotes: 0
Reputation: 5792
you're missing the 'link' property:
app.directive('myDirective',function(){
return {
link: function(scope, element, attrs){
element.click(function(){
alert('hello');
element.parent().find('.main').append('<div>Some text</div>');
})
}
}
})
Upvotes: 1