roadtocode
roadtocode

Reputation: 339

What's wrong with my Hello World AngularJS app?

This is the code, not sure why it's not working. Got the angular.min.js file in the same folder as index.html

<!doctype html>
<html lang="en" ng-app>
<head>
    <meta charset="utf-8">
    <title>Hello World</title>
</head>
<body>
    <h1 ng-controller="HelloWorldCtrl">{{helloMessage}}</h1>

    <script src="angular.min.js"></script>
    <script type="text/javascript">
        function HelloWorldCtrl($scope) {
            $scope.helloMessage = "Hello World";
        }
    </script>
</body>
</html>

Upvotes: 1

Views: 94

Answers (3)

AndyHu
AndyHu

Reputation: 1418

It's the old syntax to declare controller. Now you can't declare angualar controller as global function and you should use angular.module("appName",[]).controller("CtrlName",function(){}); instead.

Rewrite your script to:

var app = angular.module("myApp",[]);
app.controller("HelloWorldCtrl($scope){
  $scope.helloMessage = "Hello World";
}

And change your html file second line to

<html lang="en" ng-app="myApp">

Upvotes: 1

g2000
g2000

Reputation: 490

Try this one

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="angular.js"></script>
    <script type="text/javascript">
        angular.module("HelloWorldApp", [])
        .controller("HelloWorldController", function ($scope) {
            $scope.helloWorld = "Hello World";
        })
    </script>
</head>
<body ng-app="HelloWorldApp" ng-controller="HelloWorldController">
    <h1>{{helloWorld || "undefined"}}</h1>
</body>
</html>

Upvotes: 0

Daemedeor
Daemedeor

Reputation: 1013

Angular is a whole framework and not just a simple call like that. You'll need actually do something like (in a js file usually):

angular.module("myapp",[]).controller('HelloWorldCtrl', ['$scope', function($scope){
$scope.helloMessage = "hello World";
}]);

and the HTML for it is

<!doctype html>
<html lang="en" >
<head>
    <meta charset="utf-8">
    <title>Hello World</title>
    <script src="angular.min.js"></script>
</head>
<body ng-app="myapp">
    <h1 ng-controller="HelloWorldCtrl">{{helloMessage}}</h1>


    <script type="text/javascript">
    angular.module("myapp",[]).controller('HelloWorldCtrl', ['$scope', function($scope){
    $scope.helloMessage = "hello World";
    }]);
    </script>
</body>
</html>

(note this isn't best practices, but to help you get started, reference here for best practice, that i find accurate: https://github.com/johnpapa/angular-styleguide)

Upvotes: 0

Related Questions