简体   繁体   English

angularjs路由,javascript在注入的视图上不起作用

[英]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 我只是按照以下链接上的教程进行操作: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. 我完全按照页面上的描述进行操作,但是将其逐步发展为一个真正的项目,我不得不在内部页面(例如pages / about.html)中放置一些javascript代码。 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. 它不被解释为javascript代码。 and the alert is not shown 并且未显示警报

pages are injected using ng-view 页面是使用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 整个代码可以在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. 我一直在模板中使用脚本(用于延迟加载)一段时间,却不知道AngularJS并没有完成全部工作。 However, you can acomplish the task if you combine AngularJS with JQuery . 但是,如果将AngularJSJQuery结合使用,则可以完成任务。

Check the following snippet for a solution: 检查以下代码段以获取解决方案:

index.html 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.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. 如果将JQueryAngularJS交换,该解决方案将无法正常工作。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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