3

I'm trying to write a simple "Hello World" application with AngularJS. I would expect the function greeting() to print the name inserted in the text input in real time, but instead I get simply {{greeting()}} in output. What's wrong?

<!doctype html>
    <body ng-app="myApp">

    <div ng-controller="userController">
        <p>Name: <input type="text" ng-model="user.name"></p>
        <p>Surname: <input type="text" ng-model="user.surname"></p>
        <p>{{greeting()}}</p>
    </div>

    <script type="text/javascript">
        angular.module("myApp", [])
            .controller("userController",
                function ($scope) {
                    $scope.user = {name: "Mario", surname: "Rossi"};
                    $scope.greeting = function() {
                        return "Hello " +
                            $scope.user.name + " " +
                            $scope.user.surname + "!"
                    };
                });
    </script>
    </body>
    </html>

Here's an example: I would like to see Hello John Smith! instead of {{greeting()}}.

What I see

1
  • 2
    Have you included angular script somewhere? Commented Jan 31, 2020 at 8:26

1 Answer 1

3

You forgot to include the AngularJS JavaScript.

Otherwise it works fine:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body ng-app="myApp">

  <div ng-controller="userController">
    <p>Name: <input type="text" ng-model="user.name"></p>
    <p>Surname: <input type="text" ng-model="user.surname"></p>
    <p>{{greeting()}}</p>
  </div>

  <script type="text/javascript">
    angular.module("myApp", [])
      .controller("userController",
        function($scope) {
          $scope.user = {
            name: "Mario",
            surname: "Rossi"
          };
          $scope.greeting = function() {
            return "Hello " +
              $scope.user.name + " " +
              $scope.user.surname + "!"
          };
        });
  </script>
</body>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.