Warm tip: This article is reproduced from stackoverflow.com, please click
angularjs javascript

Basic function in AngularJS

发布于 2020-03-27 15:41:12

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

Questioner
Robb1
Viewed
50
Robby Cornelissen 2020-01-31 16:28

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>