简体   繁体   English

如何从指令中查找和删除DOM元素?

[英]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. 我使用bootstrap typeahead并向该元素添加指令,并在select动作中收听广播。

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. 我不能做两件事:传递我的后继id并找到并删除此DOm元素,即使id是已知的。

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. 我会摆脱您开始的指令,因为它可以很容易地被ng-repeat和更简单的代码替换。

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. 请注意,仅对数据模型进行了修改,angular将在内部处理添加/删除DOM元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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