Angular JS:在 ng-view 中加载自定义 javascript 文件

Angular JS: load custom javascript file in ng-view

我使用 Angular Js 作为示例的前端,创建了一个模板并根据需要动态加载了视图。我在示例应用程序中使用 angularjquerycusotm js。我的模板工作正常,基本结构如下:

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
  ---------------- bootstap, css etc ----------- stylesheet include
  <script src='assets/js/angular.min.js' type="text/javascript"></script>
</head>

<body>
 <div ng-view></div>
</body>

-------------------- jquery, bootstrap ---------- javascript include
<script src='lib/angularjs/angular-route.js' type="text/javascript"></script>
<script src='lib/angularjs/custom-function.js' type="text/javascript"></script>

当应用程序运行时,我的所有脚本和样式表都已成功加载。但是在我的 custom-function.js 中,我使用元素 idclasses 来执行一些工作。 custom-function.js 加载时没有定义文档结构,因为文档是使用 <div ng-view></div> 动态加载的。

我也想在我的文档中包含 <script src='lib/angularjs/custom-function.js' type="text/javascript"></script>,它是由 angular 动态加载的,但是 custom-function.js 函数不是 运行。

我是 angular 的新手,我搜索了 google,但仍然没有找到任何合适的解决方案。我怎么能解决这个问题?

在 ngRoute 的帮助下,可以加载一个包含脚本标签的模板,其中包含包含我们想要 运行.

的 javascript 代码的 js 文件

请看下面的用法示例:

http://embed.plnkr.co/AonatjhKlPMaOG6vVWW1/preview

此示例可能会帮助您找到一些解决方案,使用 'ngRoute' 模块加载您想要在 'ng-view' 中显示的内容,您可以在 .js 文件中提供说明。

    <script src="yourinstruction.js"></script>

    </head>
    <body ng-app='base'>


    <div ng-view></div>

    <script>

   var router = angular.module('base', ['ngRoute']);

    router.config(['$routeProvider',
      function($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: '/home.html',controller:'test'
          }).otherwise({

            redirectTo: '/'
          });
      }]);


    </script>
    <!--other codes-->

yourinstruction.js 文件

  router.controller('test',function ($scope) {
    <!--your instructions-->
     })
   });

您可以使用“$viewContentLoaded”解决此问题,如本教程所示: http://www.aleaiactaest.ch/2012/06/28/angular-js-and-dom-readyness-for-jquery/

另一种方法是依赖注入(Angular 方法)。本教程的第一部分向我们展示了如何使用依赖注入来包含外部库。 http://www.ng-newsletter.com/posts/d3-on-angular.html