在Angular中包含Javascript文件

时间:2019-03-15 17:04:11

标签: javascript angularjs

我有一个Angular应用程序,它将路由重定向到特定的html页面。但是如何在其中包含相关的JavaScript。

例如,如果我单击红色,它将加载red.html。但是我还需要另外加载red.js。

   <script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "main.html"
    })
    .when("/red", {
        templateUrl : "red.html";
    })
    .when("/green", {
        templateUrl : "green.html"
    })
    .when("/blue", {
        templateUrl : "blue.html"
    });
});
</script>

1 个答案:

答案 0 :(得分:-1)

您应该使用controller属性:

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        controller : "MainController"
        templateUrl : "main.html"
    })
    .when("/red", {
        controller : "RedController";
        templateUrl : "red.html";
    })
    .when("/green", {
        controller : "GreenController"
        templateUrl : "green.html"
    })
    .when("/blue", {
        controller : "BlueController"
        templateUrl : "blue.html"
    });
});
</script>
<script src="controllers.js"></script> // add controllers files

controllers.js

angular
  .module('myApp')
  .controller('MainController', function() {
   //your MainController code
});

angular
  .module('myApp')
  .controller('RedController', function() {
   //your RedController code
});

angular
  .module('myApp')
  .controller('GreenController', function() {
   //your GreenController code
});

angular
  .module('myApp')
  .controller('BlueController', function() {
   //your BlueController code
});