Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs does not load scripts within ng-view

I had some scripts specific to a view. However, the script does not seem to execute when angularjs loads the view.

Index.html

<html>   <body ng-app="adminApp">      <div ng-view=""></div>      <script src="bower_components/angular/angular.js"></script>     <script src="scripts/app.js"></script>     <script src="scripts/controllers/main.js"></script>  </body> </html> 

Main.html - loads under ng-view

hello world   <script>      alert('Hello, John!')    </script> 

In this example, when the page load, I see a basic hello world printed on the website. However, I do not get any pop up saying "Hello, John".

Any idea why I cannot load scripts specific to a certain view?


Extra info app.js

'use strict';  angular.module('adminApp', [])   .config(function ($routeProvider) {     $routeProvider       .when('/', {         templateUrl: 'views/main.html',         controller: 'MainCtrl'       })       .otherwise({         redirectTo: '/'       });   }); 

controllers/main.js

'use strict';  angular.module('adminApp')   .controller('MainCtrl', function ($scope) {     $scope.awesomeThings = [       'HTML5 Boilerplate',       'AngularJS',       'Karma'     ];   }); 
like image 643
Karan Avatar asked Aug 13 '13 22:08

Karan


1 Answers

That's the way jqLite works. If you want scripts in templates to be evaluated, include jQuery before AngularJS. If jQuery is included, the script will be evaluated. Try removing jQuery, and you see the originally observed behavior.

Updated: since some people asked for elaboration in the comments, here it is:

When a route is matched, ngView uses jqLite's (or jQuery's, if loaded) html() method to set the content of the element (the one ngView is declared on). In other words, ngView.link() does something like this:

$element.html(template) 

So it boils down to how html() is implemented in jqLite and jQuery. jqLite uses the native innerHTML property, which only sets content but doesn't evaluate scripts. jQuery, on the other hand, parses out all script tags and executes them (by constructing and appending script DOM elements to the page).

like image 81
Buu Nguyen Avatar answered Sep 23 '22 00:09

Buu Nguyen