0

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

6 Comments

I want the Whatsup to appear in the onclick
you mean as a function ??
It could be but in this case I just want the string value
because on click is function and you need to render the dom to dynamically change the function name
Thanks so far. OK this works but now the html template is built in the link function. Could I still do this using a template in a separate file? If the template was big the the method above would add an extra level of complexity.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.