繁体   English   中英

为什么外部JavaScript文件不响应AngularJS?

[英]Why is the external JavaScript file not responding to AngularJS?

这个angularJS文件不会将表达式的值显示为“ Full Name: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;
    }
}

此问题可能是由于浏览器对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服务器来加载资源。

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

如该JSfiddle所示,代码可以正常工作,因此没有其他问题。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM