javascript - 具有范围变量的 Controller 不起作用

标签 javascript angularjs

From Documentation

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

但它并没有像文档中提到的那样工作。我只是将内联脚本移动到外部文件。

PLUNKER DEMO

另外,如果我将 $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/

相关文章:

javascript - Chrome 扩展程序与其余 Web 服务通信

javascript - 适用于 Javascript 的 Onelogin SAML 工具包

javascript - jquery 插件与转换冲突 : translateY

java - 对字段进行分组操作并将喜欢的字段列表放入数组中

angularjs - 如何以编程方式创建指令元素?

angularjs - 如何在angularjs中使用正则表达式

javascript - Vuetify 组合框中更新模型的问题

javascript - 为什么带有 Node.JS 工具的 Visual Studio 2017 无法运行/调试 node.js 项目?

javascript - 以 Angular 显示图像

javascript - 如何获取最后一个元素?