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

时间:2015-03-19 13:08:43

标签: javascript jquery html angularjs dynamic-loading

我正在使用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函数未运行。

我是棱角分明的新手,我搜索了谷歌,但仍未找到任何合适的解决方案。我怎么能解决这个问题?

3 个答案:

答案 0 :(得分:3)

借助ngRoute,可以加载一个模板,其中包含一个脚本标记,其中包含js文件,其中包含我们想要运行的javascript代码。

请查看以下示例以了解用法:

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

答案 1 :(得分:0)

此示例可能会帮助您找到一些解决方案,使用“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-->
     })
   });

答案 2 :(得分:0)

您可以使用&#39; $ viewContentLoaded&#39;解决此问题。如本教程所示: 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