为什么外部JavaScript文件没有响应AngularJS

Why is the external JavaScript file not responding to AngularJS?

本文关键字:响应 AngularJS 文件 外部 JavaScript 为什么      更新时间:2023-09-26

这个angularJS文件不显示表达式的值为"全名:John Doe";而是显示"全名:{{firstName + " " + lastName}}"。我可能错过了什么?

<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>    
</head>
<body>
<div ng-app="" ng-controller="personController">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script src="C:'Users'Vincent'Documents'Python'angularjs'StraightAngularJS'personController.js"></script>
</body>
</html>

<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-app="" ng-controller="personController">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script src="personController.js"></script>
</body>
</html>

AngularJS文件结束

下面是它的外部javaScript文件:personController.js

function personController($scope) {
    $scope.firstName = "John",
    $scope.lastName = "Doe",
    $scope.fullName = function() {
        return $scope.firstName + " " + $scope.lastName;
    }
}
这可能是

因为您将脚本标记包含在包含ng-app的div 范围之外的应用<script src="personController.js"></script>

如本 JSfiddle 所示,代码确实可以正常工作,因此没有其他错误。

希望这有帮助。

此问题可能是由于 CORS(跨源资源共享)的浏览器限制造成的。要了解有关 CORS 的更多信息,请阅读 - http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

使用 Chrome,

您可以通过使用以下参数启动 Chrome 来禁用安全检查,这将允许浏览器加载来自不同域的文件:

chrome --disable-web-security 

如果您尝试从本地磁盘加载控制器。

<script src="C:'Users'[user-name]'Documents'Python'angularjs'StraightAngularJS'personController.js"></script>

必须使用以下参数启动 Chrome:

chrome --allow-file-access-from-files

但请注意,这不是推荐的方式,您最好使用 http 服务器来加载您的资源。