In AngularJS, any inline javascript code that included in HTML templates doesn't work

In AngularJS, any inline javascript code that included in HTML templates doesn't work.

For Example:

main.html file:

<div ng-include="'/templates/script.html'"></div>

And script.html file:

<script type="text/javascript">
    alert('yes');
</script>

When I open main page, I expect an alert message that say 'yes' but nothing happens. I think some security restrictions in the AngularJS is preventing inline scripts, but I couldn't find any workaround about that.

Note: I don't use jQuery or any other framework, only AngularJS 1.2.7.


jQlite does not support script tags. jQuery does, so the recommendation is to include jQuery if you need this functionality.

From Angular's Igor Minar in this discussion:

we looked into supporting script tags in jqlite, but what needs to be done to get a cross-browser support involves a lot of black magic. For this reason we decided that for now we are just going to recommend that users use jquery along with angular in this particular case. It doesn't make sense for us to rewrite one third of jquery to get this working in jqlite.

Here's the related github issue jqLite should create elements in same way as jQuery where Igor sums up, before closing the issue, with this:

This is too much craziness for jqlite, so we are not going to do it. Instead we are going to document that if you want have script elements in ng:include or ng:view templates, you should use jquery.

demo plunker with jquery


Angular uses the $sanitize on ng-include directives which strips out scripts. A better approach for templates is to create a controller for that template.

It is better to use an individual controller for templates.

In template.html

<form role="form" ng-controller="LoginController">
   <input type="text" placeholder="Email" ng-model="email">
   <input type="password" placeholder="Password" ng-model="password">
    <button class="btn btn-success" ng-click="login()">Sign in</button>
</form>

In the LoginController you can use whatever code you want

angular.module('myApp.controllers', []).
  controller('LoginController', [function() {
      alert('controller initialized');
  }])

The event triggered when ng-include adds content is $includeContentLoaded. Your scripts should be included in this event:

For example (Plucker Demo):

function SettingsController($scope, $window) {
  $scope.template={};
  $scope.template.url = "demo.html";

  $scope.$on('$includeContentLoaded', function(event){
    $window.alert('content load');
  });

}

Additionally you can set an init function using the onload attribute:

html

<div ng-include="template.url" onload="alertMe()" > </div> </div>

Controller

$scope.alertMe=function(){
    $window.alert('sending alert on load');
  }