在AngularJS项目中使用外部JS-File

时间:2017-09-20 11:13:20

标签: 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文件。 代码Sampels被复制,但我理解它们,我无法让它们运行。

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

感谢您的帮助和想法!

Chrome中的错误代码: here new Errors

1 个答案:

答案 0 :(得分:0)

您的控制器

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>