使用隔离作用域删除指令 [英] Removing Directive using Isolated Scopes

查看:29
本文介绍了使用隔离作用域删除指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个容器中有几个指令,我需要能够专门删除它们中的每一个.每个指令都在一个大的 div 中,其中还包含一个删除按钮.

I'm having several directives in a container where I need to be able to remove each of them specifically. Each directive is in a big a div which contains a remove button as well.

控制器:

app.controller('eventController', function($scope, $rootScope){;    
  $scope.removeEvent = function (id){
    console.log(id);
    $scope.$broadcast("$destroy" + id);
  }
});

指令:

app.directive('eventView', function () {
  return {
    restrict: 'E',
    replace:true,
    templateUrl: 'partials/EventView.html',
    controller: 'eventController',
    scope: {id : '@'},
    link: function(scope, element){  
        scope.$on("$destroy"+scope.id,function() {
            element.remove();
        }); 
    }
  }
});

问题是我在这一行中遇到错误 scope.$on("$destroy"+scope.id,function() { 说 id 未定义

The issue is that I'm getting an error with this line scope.$on("$destroy"+scope.id,function() { saying that id is undefined

添加指令:

app.controller('AddTimelineController', function($scope, $rootScope,$compile){
  $scope.id = 0;
  $scope.addEvent = function (){
    newElement = $compile("<event-View id=\"{{id}}\"></event-View>")($scope);
    $scope.id = $scope.id+1;
    eventContainer = angular.element(document.getElementById('eventContainer'));
    eventContainer.append(newElement);
  }
});

删除指令:

app.controller('eventController', function($scope, $rootScope){;    
  $scope.removeEvent = function (id){
    console.log(id);
    $scope.$broadcast("$destroy" + id);
  }
});

推荐答案

代替使用 $broadcast 我会使用 $watchlink 中将监听 id 变化.

Instead using $broadcast I would use $watch into link that will listen on id change.

查看 Plunker

$watch() 确实在做污垢检查,而 $broadcast()$broadcast() 便宜代码>$watch().

It's true that $watch() is doing dirt-checking vs $broadcast()and $broadcast() is cheaper than $watch().

但是,在您的情况下,您在调用 removeEvent 之前调用了 link,因此指令没有看到您使用的正确 id.

However in your case you call the link before removeEvent is called and therefore directive doesn't see proper id you use.

这篇关于使用隔离作用域删除指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆