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