0

So in Angular i'm trying to do

$scope.data = "<script> alert('hi'); </script>";

But unfortunately that doesn't work. I also tried to add ng-bind-html but without any results.

{{data}}

also I tried to load data in a script tag but that also seems not to work. Is there a way to avoid this all? For example

$scope.data = "bob";

-

 <script>
    var name = {{data}};
    </script>
Frenck
  • 6,514
  • 5
  • 22
  • 25

2 Answers2

1

You could create a directive that will load the script into DOM dynamically.

Markup

<load-script ng-if="data" data="data"></load-script>

Directive

app.directive('loadScript', function($compile){

  return {
    restrict: 'E',
    scope: {
      'data': '='
    },
    link: function(scope, element, attrs){
      element.append($compile(scope.data)(scope))
    }
  }
})

Working Plunkr

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

Your $scope will be already either within a <script> block or in a Javascript file.

Now, when/how do you want the alert to be called? If I understand correctly what you're trying to do, here's how to do it:

<div ng-click="doAlert()">
  Click here to see an alert
</div>

and in your controller:

$scope.doAlert = function() {
   alert('hi);
};
Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85
Noam
  • 587
  • 5
  • 11