【问题标题】:Include Javascript file in Angular [duplicate]在Angular中包含Javascript文件[重复]
【发布时间】:2019-03-15 17:04:11
【问题描述】:

我有一个 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>

【问题讨论】:

  • 哪个版本的角度? angularjs 标签用于 Angular 1.x,而angular 标签用于 Angular 2+。阅读标签说明。
  • 我正在使用 Angular 1.x

标签: javascript angularjs


【解决方案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
});

【讨论】:

  • 我想包含js文件。在 Controller 中不能添加这一行
  • 你应该在 red.html 中添加它,它将被加载到你的控制器的相同范围内
猜你喜欢
  • 2011-04-28
  • 1970-01-01
  • 2011-05-07
  • 2017-02-07
  • 2017-09-10
  • 2019-01-19
  • 2011-11-21
  • 2014-10-15
  • 1970-01-01
相关资源
最近更新 更多