Angularjs does not load scripts in ng-view

I had some presentation specific scenarios. However, the script does not seem to be executed 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 - loaded under ng-view

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

In this example, when the page loads, I see the main world hello printed on the website. However, I do not receive the "Hello John" pop-up message.

Any idea why I can't load scripts specific to a particular view?




Additional information 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' ]; }); 
+46
javascript html angularjs
Aug 13 '13 at 22:20
source share
2 answers

This is the jqLite way. If you want scripts in templates to be evaluated, include jQuery before AngularJS. If jQuery is enabled, the script will be evaluated. Try removing jQuery and you will see the initially detected behavior.

Updated : as some people requested clarification in the comments, here it is:

When a route maps, ngView uses jqLite (or jQuery, if loaded) the html() method to set the content of the element (declared << 20>). In other words, ngView.link() does something like this:

 $element.html(template) 

So this boils down to how html() is implemented in jqLite and jQuery. jqLite uses the native innerHTML property, which only sets content but does not evaluate scripts. On the other hand, jQuery parses all script tags and executes them (by creating and adding DOM script elements to the page).

+62
Aug 13 '13 at 22:37
source share

If I include my script, which should work with the view, how can I call it when the view is loaded? I do not want to include jquery and / or fragment my script.

To execute the <script> without loading jQuery, use jqLite to find the <script> tag and then eval innerHTML .

 app.controller("vm", function($scope, $element) { //FIND script and eval var js = $element.find("script")[0].innerHTML; eval(js); }); 

DEMO on PLNKR

See also Problem with AngularJS # 369 - jqLite should create elements just like jQuery

+1
Mar 16 '17 at 22:16
source share



All Articles