这是一个简单的示例,可让您开始使用“Controller as”语法,这是您以后应该使用的语法。您会看到很多$scope语法的示例,但它不再是将控制器绑定到视图的推荐方法。有关更多详细信息,请参阅 AngularJS.org 的有关 ngController 的文档。
Plunker:http ://plnkr.co/edit/aydvXaJNXtzdVI1mh2I4?p=preview
HTML:
<!DOCTYPE html>
<html ng-app="controllerAsDemo">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.0-rc.2/angular.js" data-semver="1.4.0-rc.2"></script>
<script src="app.js"></script>
</head>
<body >
<p ng-controller="MainController as main">Hello {{main.name}}!</p>
<p ng-controller="BillyGoatController as billyGoat">Hello {{billyGoat.name}}!</p>
</body>
</html>
JS:
var app = angular.module('controllerAsDemo', []);
app.controller('MainController', function() {
this.name = 'World';
});
app.controller('BillyGoatController', function() {
this.name = 'Billy Goat Gruff';
})