angularjsng-controller

Difficulty with Angular controller usage from old tutorial


I'm going through a basic book for Angular, and it uses a controller to set up a field. However, I don't get the expected output. Searching here and elsewhere, it looks like I'm invoking it correctly, but something's not working. Anything obviously wrong? Anything else to try? Details below. Thanks.

Document html:

<html lang="en" ng-app ng-controller="AppCtrl">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <title></title>
  <script src="js/angular.min.js"></script>
  <script type="text/javascript" src="js/controller.js"></script>
</head>
<body>
  <h1>Hello, {{name || 'World'}}</h1>
  <input type="text" ng-model="name">
</body>

controller.js:

function AppCtrl($scope) {
 $scope.name = "World";

(function closing brace lost by code formatting)

Expected output is "Hello, World", but I get "Hello, {{name || 'World'}}"


Solution

  • You are missing the ng-app and the module in controller.

     var app = angular.module('myApp', []);
    

    DEMO

    var app = angular.module('myApp', []);
    app.controller('AppCtrl', function($scope, $http) {
     $scope.name = "World";
    });
    <!DOCTYPE html>
    <html>
    <head> 
    </head>
    
    <body>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
      <div ng-app="myApp" ng-controller="AppCtrl">
      <h1>Hello, {{name || 'World'}}</h1>
      <input type="text" ng-model="name">
      </div>
    </body>
    
    </html>