TheUnit
TheUnit

Reputation: 3

Why is the external JavaScript file not responding to AngularJS?

This angularJS file does not display the value of the expression as" Full Name: John Doe"; instead it displays "Full Name: {{firstName + " " + lastName}}". What might I have missed?

<!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>

End of AngularJS file

Below is its external javaScript file: personController.js

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

Upvotes: 0

Views: 3148

Answers (2)

Rabi
Rabi

Reputation: 2220

This issue may be due to browser restriction for CORS (Cross Origin Resource Sharing). To know more about CORS, read - http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Using Chrome you can disable the security check by launching Chrome with the following parameter, which will allow the browser to load files from different domains:

chrome --disable-web-security 

If you are trying to load the controller from local disk.

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

Launching Chrome with the following parameter is required:

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

But please note that, this is not the recommended way and you better use a http server to load your resources.

Upvotes: 0

gehleh
gehleh

Reputation: 1211

This is likely because you're including your script tag to the app <script src="personController.js"></script> outside of the scope of the div containing your ng-app.

As shown in this JSfiddle, the code does work correctly, so there's nothing else wrong.

Hope this helps.

Upvotes: 1

Related Questions