简体   繁体   中英

How find and remove DOM element from directive?

I would like to make my own tag maanger. I use bootstrap typeahead and add directive to this element and listen broadcast on select action.

I can not find a way to remove tag element that had been added previously. I can not do two things: pass my suctom id and find andremove this DOm element even if id is known.

Can you help with that please?

mainApp.directive("tagsManager", ['$compile', function($compile) {
    return {
        restrict: 'A',
        link: function( scope, element, attrs ) {
            console.log("Tags in directive: " + scope.tags);
            scope.$on('tags.new', function(event, tag) {
                console.log("New tag is arrived: " + tag.name);
                var templ = "<div class=\"btn btn-default\" ng-click=\"tagClick($event)\" id=\"tag.name\">tag.name</div>"
                    .replace(/tag.name/, tag.name).replace(/tag.name/, tag.name);
                var el = angular.element(templ);
                el.attr("bind-data", tag);
//                $scope.items = teamSharedObj.teams;
                $compile(el)(scope);
                element.after(el);
            });
            scope.tagClick = function (tag) {
                console.log("Tag: " + tag);
                // TODO find a way to get id of this element and rempve it
            }
        }
    }
}])

I would get rid of the directive you started as it can easily be replaced with ng-repeat , and simpler code.

In controller:

$scope.tags=[];
$scope.typeAheadOnSelect = function( tag){
    /* perhaps do an ajax update to server here? */
    $scope.tags.push(tag);     
}
/* example of removing from array */
$scope.deleteTag=function(tag){
   /*server update by ajax, then */
   $scope.tags.splice( $scope.tags.indexOf(tag), 1);
}

In Markup:

<div ng-repeat="tag in tags" ng-click="deleteTag(tag)" id="tag.name">{{tag.name}}</div>

Note that the only modifications being made are to the data models, angular will handle adding / removing the DOM elements internally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM