简体   繁体   中英

angularjs routing, javascript does not work on injected views

I just followed the tutorial on the link below https://scotch.io/tutorials/single-page-apps-with-angularjs-routing-and-templating

I did exactly as is described on the page, but evoluting it to a real project, I had to put some javascript code inside internal pages, pages/about.html for example. and for some reason, it is not executed. even you put a single

<script>
    alert('foo');
</script>

it's not interpreted as a javascript code. and the alert is not shown

pages are injected using ng-view

<div id="main">

    <div ng-view></div>

</div>

whole code can be viewed in https://scotch.io/tutorials/single-page-apps-with-angularjs-routing-and-templating

thanks

I´ve been using scripts inside my templates (for lazy loading) for some time now without knowing that AngularJS wasn't doing the entire work. However, you can acomplish the task if you combine AngularJS with JQuery .

Check the following snippet for a solution:

index.html

<!DOCTYPE html>
<html ng-app="app">

<head>

  <meta charset="utf-8">

  <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>

</head>

<body>

  <h1>angular app</h1>

  <div ng-view></div>

  <script type="text/javascript">
    var app = angular.module('app', ['ngRoute']);

    app.config(function($routeProvider) {

      $routeProvider

        .when('/', {
        template: '<a href="#script">i´m feeling lucky!</a>'
      })

      .when('/script', {
        templateUrl: 'script.html'
      });

    });
  </script>

</body>

</html>

script.html

script successfully loaded!
<script>alert('ok');</script>

The import order is important in this case. If you swap the JQuery with the AngularJS the solution will not work.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM