【发布时间】:2017-03-27 09:58:34
【问题描述】:
我有 app.js 文件和 watchExample.js 文件,其中有一个控制器。我在 app.js 中将此控制器注入到我的应用程序中。所以我不想在我的 index.html 头中加载 watchExample.js 文件。因为如果我有很多 js 文件,我将不得不将它们加载到我的 head 标签中。所以这对我来说似乎很脏。为什么我必须加载每个额外的 js 文件,我已经在 app.js 中注入了它们?或者有没有更好的方法来做到这一点?
index.html
<!DOCTYPE html>
<html ng-app="watch">
<head>
<title>Angular Watch</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="watchExample.js"></script>
</head>
<body ng-controller="watchExample">
<div ng-view=""></div>
</body>
</html>
app.js
var app = angular.module("watch", ['ngRoute', 'watch-page']);
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'login.html'
})
.when('/watch',{
resolve: {
"check": function($location,$rootScope){
if(!$rootScope.loggedIn){
$location.path('/');
}
}
},
templateUrl: 'watch.html',
controller: 'watchExample'
})
.otherwise({
redirectTo: '/'
});
});
watchExample.js
var app = angular.module("watch-page", []);
app.controller('watchExample', ['$scope', function ($scope) {
$scope.counter = -1;
$scope.$watch('myText', function (newValue, oldValue) {
$scope.counter++;
if($scope.counter === 50){
alert("Yeter artık "+$scope.counter+" kere değiştirdin!");
}
$scope.oldVal = oldValue;
$scope.newVal = newValue;
});
}]);
【问题讨论】:
-
好吧,Angular 不会像你想象的那样注入代码。但是,您可以使用一些工具,因此您不必在 html 中手动添加每个脚本标记,例如 Gulp
标签: javascript angularjs ngroute