Angularjs ng-click不在ng-bind-html-unsafe下触发

时间:2013-06-19 14:57:37

标签: angularjs angularjs-directive angularjs-scope angular-ui

这是指令

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;

    }


};

});

并在控制器中将链接放入msg var

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

然而,ng-click不会被触发 任何人

1 个答案:

答案 0 :(得分: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/