0

Im making a embedable widget and i need to generate a unique JavaScript snippet for the user to copy past into there site. For simplicity i killed most of the code.

widget-generator.js

.directive('widgetGenerate',function() {
        return {
            restrict: 'AE',
            replace: true,
            templateUrl: 'embed.html', // file i need to generate
            scope: {
                "height": "@"
            }
        };
    });

embed.html

<a height='{{height}}'> // WORKS!
</a>
<script type="text/javascript">
  var something = {{height}}; // DOES NOT WORK!!!!!!!!!!!!!!!!!!!!!!
</script>

On page for user to copy past:

<textarea>
  <widget-generate height = '300'/>
</textarea>

Desired text output:

 <a height='300'> </a>
 <script type="text/javascript">
    var something = 300; 
 </script>

Problem is i cannot generate the JavaScript section like this. How can i do this in angularjs?

7
  • Instead of including the javascript in your template, can you set what you want on $window in a controller for the directive? $window.something = $scope.height; Commented Nov 24, 2015 at 19:36
  • the textarea needs to display in plain text the final javascript code, if i use your method the final code would look like this: var something = $window.something; instead of var something = 300; Commented Nov 24, 2015 at 19:40
  • So you don't want the code to run? Just display? Commented Nov 24, 2015 at 19:47
  • yes thats the plan, if possible both would be nice Commented Nov 24, 2015 at 19:48
  • Have you tried escaping the template? "<" -> "&lt;", ">" -> "&gt;", etc. Commented Nov 24, 2015 at 19:51

1 Answer 1

1

I made a JSFiddle for it to get you in the right direction.

HTML

<div ng-app="myApp">
    <widget-generate height="300"></widget-generate>
</div>

JavaScript

var app = angular.module("myApp", []);

app.directive('widgetGenerate',[function() {
    return {
        restrict: 'AE',
        replace: true,
        template:   '<textarea>' + 
                      '&lt;a height="{{height}}"&gt;\r\n' +
                      '&lt;/a&gt;\r\n' +
                      '&lt;script type="text/javascript"&gt;\r\n' +
                      '\tvar something = {{height}};\r\n' +
                      '&lt;/script&gt;' +
                    '</textarea>',
        scope: {
            "height": "@"
        }
    };
}]);
Sign up to request clarification or add additional context in comments.

Comments

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.