3

这是指令Angularjs NG-点击下不烧NG绑定,HTML不安全

aomApp.directive('aomAlert', function ($rootScope,$compile) { 
return { 
    restrict:'EA', 
    transclude:true, 
    replace:true, 
    scope: {type: '=', msgCollection: '=', close: '&'}, 
    controller: function ($scope, $element, $attrs,$compile) { 
     $scope.show = false; 

     $scope.$watch('msgCollection', function(selectedPlan) { 
      $scope.show = ($scope.msgCollection.length > 0); 
     });      
    }, 
    template: 
     "<div class='alert' ng-class='type && \"alert-\" + type' ng-show='show'>" + 
     " <button ng-show='closeable' type='button' class='close' ng-click='show = false;close();'>&times;</button>" + 
     " <ul>" + 
     "  <div ng-repeat='msg in msgCollection'><li><div ng-bind-html-unsafe=msg></div></li></div>"+ 
     " <ul>" + 
     "</div>", 
    link: function($scope, $element, $attrs) { 
     $scope.closeable = "close" in $attrs; 

    } 


}; 

});

和我把链接放入味精VAR

msg = msg.replace("[", "<a href='javascript:return false' ng-click='alert()'>"); 
       msg = msg.replace("]", "</a>"); 

控制器然而NG单击犯规被触发 任何人?

回答

1

把东西放入html-bind-unsafe不会编译它。你必须告诉元素用范围进行编译。 $ compile:http://docs.angularjs.org/api/ng $ compile

编辑好的,你不需要在评论中使用$ compile。还有的去了解这样做有两种方式,一种是你告诉clickme调用的范围$ parent.clickme:

scope.clickme = function(){ 
    scope.$parent.clickme(); 
}; 

小提琴:http://jsfiddle.net/a4ang/3/

另一种是你在clickme传递作为一个属性,指令:

scope: { 
    data: '=', 
    clickme: '=' 
}, 

的Html

<toggle-buttons data="data" clickme="clickme"></toggle-buttons> 

更新小提琴:http://jsfiddle.net/a4ang/4/

+0

我经历了文档,但仍然对此问题感到困惑,我尝试编译模板中的html-bind-unsafe,如下所示:

  • "+$compile("
    “)+”
  • “。但它仍然不起作用 – user2501711

    +0

    不,你必须在你的指令后做。为什么你用这种方式使用html-bind-unsafe?它通常保留给角度不属于的部分。 –

    +0

    你指的是什么意思?你能给我这个代码吗?谢谢你的回复 – user2501711