【问题标题】:Why is the external JavaScript file not responding to AngularJS?为什么外部 JavaScript 文件没有响应 AngularJS?
【发布时间】:2014-12-24 02:47:15
【问题描述】:

这个 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;
    }
}

【问题讨论】:

  • 尝试根据文档使用适当的控制器构造函数。已放弃对全局函数的支持。最好使用脚本文件的相对路径
  • 在您开始想知道为什么脚本不起作用之前,请确保首先加载它!如果您使用的是 Chrome,请检查 sources 选项卡以查找您的文件 personController.js 是否存在。顺便说一句,你为什么有两个body 标签?...

标签: javascript html angularjs


【解决方案1】:

这可能是因为您将脚本标签包含在应用程序 &lt;script src="personController.js"&gt;&lt;/script&gt; 中,超出了包含 ng-app 的 div 范围。

JSfiddle 所示,代码运行正常,没有其他问题。

希望这会有所帮助。

【讨论】:

  • 也学到了,不需要外部jsp文件的相对文件位置。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 2014-04-28
    • 2020-10-16
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多