javascript - AngularJS 模型未将数据加载到 View 中

标签 javascript angularjs

所以我正在遵循一个非常基本的 AngularJS 教程,发现 here

我已经进行了大约第 10 步,但我的 View 中没有显示任何内容。给出了什么?

这是index.html的内容:

<html>
  <head>
    <title>My Angular App!</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-app="flapperNews" ng-controller="MainCtrl">
    <div ng-repeat="post in posts">
        {{post.title}} - upvotes: {{post.upvotes}}
    </div>
  </body>
</html>

这是app.js的注释:

angular.module('flapperNews', [])
.controller('MainCtrl', [
'$scope',
function($scope){
  $scope.test = 'Hello world!';
}]);

$scope.posts = [
  {title: 'post 1', upvotes: 5},
  {title: 'post 2', upvotes: 2},
  {title: 'post 3', upvotes: 15},
  {title: 'post 4', upvotes: 9},
  {title: 'post 5', upvotes: 4}
];

最佳答案

问题是您试图在任何 Angular 上下文(即 MainCtrl Controller )之外声明 $scope.posts

html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>My Angular App!</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-app="flapperNews" ng-controller="MainCtrl">
    <div ng-repeat="post in posts">
        {{post.title}} - upvotes: {{post.upvotes}}
    </div>
  </body>

</html>

js

angular.module('flapperNews', [])
  .controller('MainCtrl', [
    '$scope',
    function($scope) {
      $scope.test = 'Hello world!';

      // We are inside a controller here:
      $scope.posts = [{
        title: 'post 1',
        upvotes: 5
      }, {
        title: 'post 2',
        upvotes: 2
      }, {
        title: 'post 3',
        upvotes: 15
      }, {
        title: 'post 4',
        upvotes: 9
      }, {
        title: 'post 5',
        upvotes: 4
      }];
    }
  ]);

http://plnkr.co/edit/ybJgc3?p=preview

关于javascript - AngularJS 模型未将数据加载到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31976211/

相关文章:

javascript - 以编程方式向根 Node 对象添加函数

javascript - 如何将查询字符串数据或任何值从 url 传递到 AngularJS 中的 Controller 函数?

javascript - Angular watch 功能在 safari 浏览器中不起作用

angularjs - ng-show 使用按钮选择不同的真假方法

angularjs - 从 Travis 上的 Protractor 在 Sauce Labs 上运行 e2e 测试

javascript - 创建一个 'remove div' 链接

javascript - 假设我无法使用 Chrome 控制台更改页面 css,我可以记录页面内容并设置样式吗?

javascript - 需要帮助了解 Node JS/Passport JS 的工作原理

javascript - 如何将外部 javascript 文件集成到 PugJS 中?

javascript - 如果数组第一个元素中的字符串包含数组第二个元素中字符串的所有字母,则返回 true