Sun
Sun

Reputation: 4708

Passing string in angular directive

I have an angular directive:

angular.module("App").directive("myButtons", function () {
    return {
        restrict: "E",
        scope: 
            {
                teststring: '@'
            },
        templateUrl: "test.html"
    }
});

with the following template:

<div>
    <input type="button" onclick="teststring" value="Hi" />
</div>

This is the directive in the HTML:

<my-buttons teststring="Whatsup" />

I want the value that I pass into teststring to appear in the rendered html.

At the moment I just get onclick="teststring".

What am I doing wrong. I've tried added {{ }} on the template and also @, = and & on the scope value.

Upvotes: 0

Views: 247

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

you can use ng-bind-html to set up the html in the js and dynamically render to the DOM

change the template to this

And add a link function to the directive like this

 angular.module("app").directive("myButtons", function($sce) {
     return {
         restrict: "E",
         scope: {
             teststring: '@'
         },
         template: `<div>
                <div ng-bind-html="trust(sampleCode)">
            </div>`,
         link: function(scope) {
             scope.sampleCode = '<input type="button" onclick="' + scope.teststring + '" value="Hi" />';

             scope.trust = function(html) {
                 return $sce.trustAsHtml(html);
             }
         }
     }
 });

also, inject the $sce as a service to the directive

Demo

angular.module("app",[])
.controller("ctrl",function($scope){


})
 angular.module("app").directive("myButtons", function($sce) {
 return {
     restrict: "E",
     scope: {
         teststring: '@'
     },
     template: `<div>
            <div ng-bind-html="trust(sampleCode)">
        </div>`,
     link: function(scope) {
         scope.sampleCode = '<input type="button" onclick="' + scope.teststring + '" value="Hi" />';

         scope.trust = function(html) {
             return $sce.trustAsHtml(html);
         }
     }
 }
 });
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <my-buttons teststring="Whatsup" />
</div>

Upvotes: 1

Related Questions