AngularJS 表达式不适用于添加控制器

AngularJS expression not working with adding controller

当我将 ng-controller 添加到我的 index.html 时,表达式显示为 {{name || "Hello"}}和{{年龄|| "my friend"}}。在我删除 ng-controller 后,表达式 aslo 无法工作。

这是controller.js

var PersonCtrl = function($scope){
    $scope.name = 'sky';
    $scope.age = 18;

    $scope.$watch('name', function(){
        console.log($scope.name);
    });

    $scope.$watch('age', function(){
        if($scope.age < 18){
            console.error('not correct');
        }
    });
};

这是index.html

<!DOCTYPE html>
<!-- whole page is applied in AngularJS -->
<html ng-app>
<head>
  <meta charset="utf-8">
  <title>Learning of AngularJS</title>
  <!-- link with AngularJS -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <!-- <link rel="stylesheet" href="css/home.css"> -->
  <link rel="stylesheet" href="css/index.css">
</head>

<body>
<div id ="test" ng-controller="PersonCtrl">

 <h1>Name:</h1>
 <input size="35" style="height:50px" type="text" ng-model="name"
        placeholder="Enter your message, please.">

<h1> Age: </h1>
  <input size="35" style="height:50px" type="text" ng-model="age"
         placeholder="Enter your name, please.">
        <hr>
  <h1>{{name || "Hello"}}</h1>
  <h1>{{ age || "my friend" }}!</h1>

</div>
</body>
</html>

将您的 html 标签更改为

<html ng-app="myApp">

controller.js :

// Define the Module. Only once in your code.
var myApp = angular.module('myApp', []);

// Define a controller for you module.
    myApp.controller('PersonCtrl', ['$scope', function ($scope) {
        $scope.name = 'sky';
        $scope.age = 18;

        $scope.$watch('name', function () {
            console.log($scope.name);
        });

        $scope.$watch('age', function () {
            if ($scope.age < 18) {
                console.error('not correct');
            }
        });
    }]);