[当我将ng-controller添加到index.html时,该表达式显示为{{name || “ Hello”}}和{{age || “我的朋友” }}。我删除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');
}
});
}]);