我有一个单页应用程序,我想将我的代码分成两个独立的js文件,如下所示 - Script1.js -
var app = angular.module("AngularJs", ["ui.router"])
.config(function ($stateProvider) {
$stateProvider
.state("home", {
url:"/home",
templateUrl: "Template/Home.html",
controller: "homeController",
controllerAs: "homectrl"
})
.state("courses", {
url: "/courses",
templateUrl: "Template/Courses.html",
controller: "coursesController",
controllerAs: "Coursectrl"
})
.state("newregistration", {
// url: "/students",
templateUrl: "Template/NewRegistration.html",
controller: "newregistration",
controllerAs: "newregistrationctrl"
})
})
我为所有州定义了控制器
.controller("homeController", function () {
this.message = "Home Page";
})
.controller("coursesController", function () {
this.courses = ["C#", "VB.NET", "SQL Server", "ASP.NET"];
this.message = "Courses Page";
})
Now problem is that i want to define other controller on other script file -
Script2.js -
.controller("newregistration", function () {
this.meassage = "New Employee Registration sfdsf";
})
如何将代码分成两个不同的js文件。
答案 0 :(得分:1)
分离示例
<强> App.js 强>
var app = angular.module("AngularJs", ["ui.router"])
<强> Config.js 强>
app.config(function ($stateProvider) {
$stateProvider
.state("home", {
url:"/home",
templateUrl: "Template/Home.html",
controller: "homeController",
controllerAs: "homectrl"
})
.state("courses", {
url: "/courses",
templateUrl: "Template/Courses.html",
controller: "coursesController",
controllerAs: "Coursectrl"
})
.state("newregistration", {
// url: "/students",
templateUrl: "Template/NewRegistration.html",
controller: "newregistration",
controllerAs: "newregistrationctrl"
})
})
<强> Controllers.js 强>
app.controller("homeController", function () {
this.message = "Home Page";
})
app.controller("coursesController", function () {
this.courses = ["C#", "VB.NET", "SQL Server", "ASP.NET"];
this.message = "Courses Page";
})
答案 1 :(得分:1)
定义应用
app.js
var app = angular.module('demoApp',[]);
将您的控制器放在这样的单独文件中
<强> HomeCtrl.js 强>
angular.module('demoApp').controller("homeController", function () {
this.message = "Home Page";
});
<强> CoursesCtrl.js 强>
angular.module('demoApp').controller("coursesController", function () {
this.courses = ["C#", "VB.NET", "SQL Server", "ASP.NET"];
this.message = "Courses Page";
});
<强> RegistrationCtrl.js 强>
angular.module('demoApp').controller("newregistration", function () {
this.meassage = "New Employee Registration sfdsf";
});
然后,您的HTML将包含该应用并使用控制器
<script src="app.js"></script>
<script src="HomeCtrl.js"></script>
<script src="CoursesCtrl.js"></script>
<script src="RegistrationCtrl.js"></script>
<body ng-app="demoApp">
<div ng-controller='HomeCtrl'>
This will access home controller
</div>
<div ng-controller='CoursesCtrl'>
This will access courses controller
</div>
<div ng-controller='RegistrationCtrl'>
This will access registration controller
</div>
</body>