【问题标题】:Angular remove Element角度移除元素
【发布时间】:2014-07-13 03:20:22
【问题描述】:

我有一个指令:

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

指令的控制器:

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

在根作用域中有多个相同指令的实例。每个指令都是一个 div,其中有一个删除按钮,该按钮绑定到控制器定义中的 removeEvent 方法。

问题是,当在其中一个 div(来自 eventView 指令)中按下删除按钮时,所有 div 都将被删除。我只希望删除正在广播销毁的当前指令。我知道它是因为我正在广播 $scope.$broadcast("$destroy") 但我怎样才能只删除当前范围,是否有仅适用于当前范围的预定义方法

【问题讨论】:

  • 这些 div 是通过 ng_repeat 呈现还是有一些唯一标识符??
  • 您应该调查孤立的范围。您的指令需要知道它所指的范围。这是一篇好文章:sitepoint.com/practical-guide-angularjs-directives
  • @HarishR,它不是 ng_repeat 的一部分

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

如果您使用的是 ng-repeat,那么您可以使用 $index 作为这些 div 的唯一标识符... 只需更新您的代码,如下所示:

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

并使用标识符广播事件

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

如果 div 不是 ng-repeat 的一部分,那么您将需要某种标识符来识别要销毁的 div...

【讨论】:

  • 所以,我明白了,我应该将 scope: {identifier : '@'} where @ 替换为标识符
  • 无论你在哪里使用这个指令,你都需要传递标识符:<event-view identifier="{{$index}}"></event-view>
  • 在链接函数中,function(scope, element){ scope.$on("$destroy" + identifier,function() { element.remove(); });我收到标识符不存在的错误
  • 标识符是我将保留在范围变量中的值,问题是每当我更新范围标识符时,它都会在所有指令范围中更新
  • 使用隔离范围,就像我的示例中的那样..为每个指令保留单独的实例...您也会收到该错误,因为我猜您没有添加隔离范围..跨度>
猜你喜欢
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 2013-02-07
相关资源
最近更新 更多