温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Basic function in AngularJS

javascript - AngularJS中的基本功能

发布于 2020-03-27 15:52:03

我正在尝试使用AngularJS编写一个简单的“ Hello World”应用程序我希望函数greeting()可以实时打印在文本输入中插入的名称,但我只会{{greeting()}}在输出中得到怎么了?

<!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>

这是一个示例:我希望看到Hello John Smith!而不是{{greeting()}}

我所看到的

查看更多

查看更多

提问者
Robb1
被浏览
33
Robby Cornelissen 2020-01-31 16:28

您忘记了包含AngularJS JavaScript。

否则,它可以正常工作:

<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>

发布
问题

分享
好友

手机
浏览

扫码手机浏览