javascriptangularjsangularjs-controller

AngularJS expression not working with adding controller


When i added ng-controller to my index.html, the expression show up as {{name || "Hello"}} and {{ age || "my friend" }}. After i removed the ng-controller, expressions aslo cannot work.

it is the 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');
        }
    });
};

it is the 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>

Solution

  • Change your html tag to

    <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');
                }
            });
        }]);