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,474
  • 5
  • 21
  • 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
  • 130,886
  • 22
  • 223
  • 289
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);
};
Tom Sarduy
  • 16,878
  • 8
  • 67
  • 83
Noam
  • 577
  • 5
  • 11