我想将角度移动到自己的.js
文件,因此我查看了Using an HTML button to call a JavaScript function。
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
据我了解,当我点击按钮时必须触发一个事件,所以我尝试在w3schools上关注this示例
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click Me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
</body>
</html>
它只是计算按钮被点击的次数并且有效。但是,当我将<script>
移动到它自己的.js时,找不到该函数。我错过了什么吗?或许依赖?
新文件:
HTML:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click Me!</button>
<p>{{ count }}</p>
</div>
</body>
</html>
的.js
<script>
var app = angular.module('myApp', ['ngRoute']);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
答案 0 :(得分:2)
所以有两个问题。
首先,在您的.js
文件中,您可以删除<script>
代码。你只需要在html文件中使用javascript。
其次,在.html
文件中,您需要添加对脚本文件的引用。这需要低于angular脚本,因为它依赖于该脚本,所以只需在角度脚本下方的html中添加<script src="[link to your script file]"></script>
。
<强> html的强>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click Me!</button>
<p>{{ count }}</p>
</div>
</body>
</html>
<强> app.js 强>
var app = angular.module('myApp', ['ngRoute']);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});