Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

angularjs - Rendering directives within $sce.trustAsHtml

I've included a Plunker here: http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=preview

I'm trying to add a button to the DOM and when clicked should execute the function bound to it. In this case it should alert "testing". Here is the code.

controller

app.controller('MainCtrl', function($scope, $sce) {
        $scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');  

        $scope.testAlert = function () {
            alert('testing')
        };
});

HTML

<body ng-controller="MainCtrl">
    <div ng-bind-html="trustedHtml"></div>
</body>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$sce.trustAsHtml and ng-bind-html are not meant to build HTML with directives. This technique will not work.

This is because angular works by first compiling and then linking. See the conceptual overview for a good explaination.

In short, by the time you link the HTML defined in your trustAsHtml, it is too late for angular to compile (and therefore understand) the ng-click directive.

In order to dynamically add HTML, you should be looking at the $compile service (and/or directives). Docs are here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...