Reputation: 18619
i am trying to remove an element using directive
i found a working example http://jsfiddle.net/qDhT9
and i tried to append a new element and having the thing as http://jsfiddle.net/qDhT9/140
var app = angular.module('myApp', []);
app.directive('removeOnClick', function() {
return {
link: function(scope, elt, attrs) {
scope.remove = function() {
alert('here');
elt.html('');
};
elt.append('<a href class="close" style="float:right;padding-right:0.3em" ng-click="remove()">×</a>');
}
}
});
but this
one does not worked.
Why and how to make the second one work.
Upvotes: 0
Views: 1140
Reputation: 171669
You need to use $compile
for any html you insert that includes angular directives:
app.directive('removeOnClick', function($compile) {
return {
link: function(scope, elt, attrs) {
scope.remove = function() {
alert('here');
elt.html('');
};
var link = $compile('<a href class="close" ng-click="remove()">LINK</a>')(scope)
elt.append(link);
}
}
});
Also note that most of the time you can do this sort of removal by managing the model data and removing the data and let angular manage the dom. For example removing a row in an ng-repeat
you would use a button to remove that item from the data array and angular would then remove it from the dom for you
Upvotes: 2
Reputation: 626
You need to bind a function to an element to trigger the remove function
try this,
var app = angular.module('myApp', []);
app.directive('removeOnClick', function() {
return {
link: function(scope, elt, attrs) {
scope.remove = function() {
alert('here');
elt.html('');
};
elt.bind('click', function() {
alert('here');
elt.html('');
});
elt.append('<a href class="close" style="float:right;padding-right:0.3em" ng-click="remove()">×</a>');
}
}
});
Upvotes: 0