Search code examples
angularjsangularjs-directiveangularjs-scope

HTML and JAVASCRIPT Editor in Angularjs


I have an angularjs 1.5.8 application created using Jhipster.

For my website I want to make a HTML and JAVASCRIPT editor. Need to allow user to write HTML Code but JAVASCRIPT also.

Using this library I know I can achieve the follow.

https://github.com/incuna/angular-bind-html-compile

1: Bind HTML Code. 2: Bind Angular code if present in HTML

Eg: <h1>{{$scope.test}}</h1>

Would render correct value in the scope.

But what about something like this in the html

<script>
console.log($scope);
</script>

I get a $scope not defined error, somehow the $scope value is not available in the script tag.

If anyone curious that why I need to do this because we want to provide users of the application to create there own Angularjs Forms.


Solution

  • I solved using ng-include, here is the example source.

    I wanted to do two things.

    1: Make ng-include work from a scope variable which will contain html and javascript.

    2: In the included string if I have a script tag I wanted it to render correct in the ng-include.

    To achieve the #1 I did the following.

    Used $templateCache service.

    Sample code.

    $templateCache.put('template-form', vm.html + vm.script);
    

    For point #2

    I made sure the script tag is structured in the following way.

    <script>
    (function() {
        'use strict';
    
      angular.module('myApp').controllerProvider.register('AppTemplateController',AppTemplateController);
      AppTemplateController.$inject = ['$scope'];
    
      function AppTemplateController($scope){
        // WRITE YOUR CODE IN THIS CONTROLLER
        // YOU CAN WRITE YOUR VARIABLES/FUNCTIONS HERE.
        // MAKE SURE TO CALL THE method "vm.submitForm", to submit your form and pass the form object.
      };
    
    })();
    </script>
    

    This way you can inject a controller.

    My requirement was very very specific to my projecct, I am not sure if others who did not face this issue even would understand what I am talking about. But for those who do face it, I hope you it helpful