0

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()">&times;</a>');
            }
        }
    });

but this

one does not worked.

Why and how to make the second one work.

0

2 Answers 2

2

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

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

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()">&times;</a>');
        }
    }
});

1 Comment

I think he wants the elt.append() to execute. You only had to call ng-click on the element to run remove()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.