The syntax
InvoiceController as invoice
tells Angular to instantiate the controller and save it in the variable invoice in the current scope.We also changed all expressions in the page to read and write variables within that controller instance by prefixing them with
invoice
.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js" data-require="angular.js@1.3.x"></script>
<script src="app.js"></script>
</head>
<body ng-controller="InvoiceController as invoice">
<p>Hello {{invoice.name}}!</p>
</body>
</html>
JS
var app = angular.module('plunker', []);
app.controller('InvoiceController', function() {
this.name = 'World';
});
但它并没有像文档中提到的那样工作。我只是将内联脚本移动到外部文件。
另外,如果我将 $scope
传递给 Controller 函数,为什么它不起作用
app.controller('InvoiceController', function($scope) {
$scope.name = 'World';
});
最佳答案
你忘了设置 ng-app
<html ng-app="plunker">
<!-- REST OF HTML -->
</html>
关于javascript - 具有范围变量的 Controller 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29140216/