Nagendra555 Nagendra555 - 9 days ago 5
AngularJS Question

Angular js binding expression does not show value

The index.html page looks like this.

<!DOCTYPE html>
<html ng-app>
<head>
<script type="text/javascript" src="/js/script.js"/>
<script data-require="angular.js@*" data-semver="1.3.0-beta.14" src="http://code.angularjs.org/1.3.0-beta.14/angular.js"></script>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body ng-controller="MainController">
<div>
<h1>{{message}}</h1>
<div>
{{person.firstName}}
</div>
</div>
</body>
</html>


The script.js file looks like this:

var MainController = function($scope) {
var person = {
firstName : "Nagendra"
};
$scope.person = person;
$scope.message = "Hello Angular!";
};


But when I boot up the application my page shows :

{{message}}

{{person.firstName}}


and not the values that it should. Am I missing something here? I am using spring boot.
I have debugged the chrome and have seen the js file loading properly, it even hits the debugger point in the js file,hence the file loading is not the problem i suppose.


UPDATE- THIS WORKED


var MainController = function($scope) {
var person = {
firstName: "Nagendra"
};
$scope.person = person;
$scope.message = "Hello Angular!";
};


angular.module('mainApp', [])
.controller('MainController', MainController);


index.html

<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<script data-require="angular.js@*" data-semver="1.3.0-beta.14" src="http://code.angularjs.org/1.3.0-beta.14/angular.js"></script>
<script type="text/javascript" src="/js/script.js"></script>
<meta charset="UTF-8">
<title>Test Page</title>
</head>
<body ng-controller="MainController">
<div>
<h1>{{message}}</h1>
<div>
{{person.firstName}}
</div>
</div>
</body>
</html>

Answer

Since angular 1.3+ global function declaration of controller haven't been supported. So you have first create an angular module and then bind all of its angular component to it.

Also move /js/script.js right after angular.js reference with closing </script> tag.

Code

angular.module('mainApp', [])
.controller('MainController', MainController)
function MainController($scope) {
    var person = {
        firstName: "Nagendra"
    };
    $scope.person = person;
    $scope.message = "Hello Angular!";
};

Then do add mainApp module inside ng-app directive like ng-app="mainApp" on html tag.

Demo Here

Comments