0

So I am following a very basic AngularJS tutorial, found here

I have gotten to about step 10 but nothing is being displayed in my view. What gives?

Here is the contents of 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>

Here is the comments of 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}
];

1 Answer 1

3

the problem is that you're trying to declare $scope.posts outside of any angular context, namely the MainCtrl controller.

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

Sign up to request clarification or add additional context in comments.

2 Comments

Damn, I thought it existed in a global context. This worked and I'll accept in seven minutes
Angular actually tries to prevent you from creating anything within a global context. The global namespace should be kept clear and anything you need to access in other components should be injected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.