2015-10-06 48 views
0

我试图用指令通过点击删除元素的角度

删除的元素我发现了一个工作示例 http://jsfiddle.net/qDhT9

,我想追加一个新元素,并具有事情 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>'); 
      } 
     } 
    }); 

但这

一个不工作。

为什么以及如何使第二个工作。

回答

2

您需要在插入使用$compile任何HTML包括角指令:

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); 
     } 
    } 
}); 

另外请注意,大多数情况下,您可以通过管理模型数据并删除数据并让角度管理e dom。例如,在一个ng-repeat移除一行你可以使用一个按钮,从数据数组中删除该项目,然后角度会从DOM中删除它为您

DEMO

0

您需要的功能结合到一个元素触发remove函数

试试这个,

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>'); 
     } 
    } 
}); 
+2

我认为他想了' elt.append()'来执行。您只需在元素上调用'ng-click'来运行remove() – Dayan