Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: ng-bind-html doesn't work with button tag

I am having problem to print out an input type button dynamically in a div "ng-bind-html".

HTML template:

<input type="button" value="Add" ng-click="add()">
<div ng-bind-html="snippet"></div>

Controller:

$scope.add = function() {
   $scope.snippet = "<input type='button' value='Test' ng-click='myFunc()'><b>Test 2</b>";
}

The tag input is removed and then I see just the "bold" text Test 2.

Thanks

like image 820
Danilo Paone Avatar asked Mar 30 '14 13:03

Danilo Paone


People also ask

Does ng-bind bind the application data to HTML tags in AngularJS?

ng-bind directive binds the AngularJS Application data to HTML tags. ng-bind updates the model created by ng-model directive to be displayed in the html tag whenever user input something in the control or updates the html control's data when model data is updated by controller.

How does ng-bind HTML work?

The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable, or expression, changes, the content of the specified HTML element will be changed as well.

Is ng-bind HTML safe?

The ng-bind-html directive is a secure way of binding content to an HTML element. When you are letting AngularJS write HTML in your application, you should check the HTML for dangerous code. By including the "angular-sanitize.


1 Answers

For some reason your html tag is mark as unsafe by angular js. If you sure that your snippet text is safe, you can $sce.trustAsHtml it before adding it to the $scope.snippet.

app.controller('yourCtrl', ['$scope', '$sce', function($scope, $sce){
    $scope.add = function(){
        var text = "<input type='button' value='Test'><b>Test 2</b>";

        // mark it as clean
        text = $sce.trustAsHtml(text);

        $scope.snippet = text;
    };
}]);
like image 174
Iqbal Fauzi Avatar answered Oct 03 '22 16:10

Iqbal Fauzi