将脚本移动到自己的js文件

时间:2018-01-31 22:19:16

标签: html angularjs

我想将角度移动到自己的.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> 

1 个答案:

答案 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;
});