javascript - 在 AngularJS 项目中使用外部 JS 文件

标签 javascript html angularjs

index.html:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

</script>
<script src="./assets/namesController.js"></script>

<body ng-app="myApp">

    <!-- Method call from external JS files -->
    <br>
    <div ng-controller="ryanContrler">
        My first name : <input type="text" ng-model="ryanFirstname"> 
        <br> My last name : <input type="text" ng-model="austinLastname">        
        <br> My full name : {{fullName()}}
    </div>

</body>

</html>

namesController.js:

angular.module('myApp').controller('ryanContrler', ['$scope', function ($scope{
    $scope.ryanFirstname = "Ryan",
    $scope.austinLastname = "Austin",
    $scope.fullName = function() {
        return $scope.ryanFirstname + " " + $scope.austinLastname;
    }

}]);

嘿伙计们,

我尝试在我的 AngularJS 项目中使用外部 JS 文件,但无论我尝试什么,它似乎都无法识别该 JS 文件。 代码样本是复制的,但我理解它们,但我无法让它们运行。

我将JS粘贴到assets文件夹中。 html 文件位于 src 文件夹中。

感谢您的帮助和想法!

Chrome 中的错误代码: here new Errors

最佳答案

你的 Controller

var agentApp = angular.module('myApp',[]);

agentApp.controller('ryanContrler',function ($scope){
    $scope.ryanFirstname = "Ryan",
        $scope.austinLastname = "Austin",
        $scope.fullName = function() {
            return $scope.ryanFirstname + " " + $scope.austinLastname;
        }

});

您的 HTML 应如下更改

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <script type="text/javascript" src="angular/angular.js"></script>

    <script src="assets/namesController.js"></script>
</head>


<body >

<!-- Method call from external JS files -->
<br>
<div ng-controller="ryanContrler">
    My first name : <input type="text" ng-model="ryanFirstname">
    <br> My last name : <input type="text" ng-model="austinLastname">
    <br> My full name : {{fullName()}}
</div>

</body>

</html>

关于javascript - 在 AngularJS 项目中使用外部 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46320546/

相关文章:

javascript - 无法在 PHP 文件中集成一些 JS 代码

javascript - Vuetify 步进器垂直和非线性问题

html - Golang 提供 html 文件

javascript - 显示重复值

javascript - 解析 Angular 提前输入组件中的数据不起作用

javascript - 这是正确的方法吗?我不想使用原型(prototype)而只是类构造函数上的方法

javascript - 使用 Ajax 的 Promise 加上超时?

html - 是否有任何为可访问性目的而设计的微格式?

javascript - 如何构建多部分 MIME 请求并使用 AngularJS 的 $http 方法发布它?

javascript - jQuery parseJSON 失败