1

I try to display some variable of my controller, but the output is just {{UserCtrl.user}} instead of the content of UserCtrl.user.

I got the following file structure:

  • index.html
  • scripts/app.js

This is the code of index.html:

<!doctype html>
<html lang="en" ng-app="birdsnest">
<head>
    <meta charset="utf-8">

    <title>Birdsnest</title>

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap-theme.css">
</head>
<body>
    <div ng-controller="UserController as UserCtrl">
        {{UserCtrl.user}}
    </div>

    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
    <script src="bower_components/angular/angular.js"></script>

    <script src="scripts/app.js"></script>
</body>
</html>

scripts/app.js:

(function() {
  var app = angular.module('birdsnest', []);

  app.controller('UserController', ['scope', function($scope) {
    $scope.user = 'Michael';
  }]);
})();
5
  • I can't see the ng-app. Where you define the app? Commented Nov 7, 2015 at 19:38
  • Yes, it's in the html tag: <html lang="en" ng-app="birdsnest"> Commented Nov 7, 2015 at 19:39
  • Sorry. missed that. Do you see any errors on console? Commented Nov 7, 2015 at 19:40
  • You need to put the JS includes on top of everything, not below. (in the <head> section) Commented Nov 7, 2015 at 19:47
  • Done, but same result as mentioned in question. Commented Nov 7, 2015 at 19:48

2 Answers 2

2

Change this line:

app.controller('UserController', ['scope', function($scope) {

To:

 app.controller('UserController', ['$scope', function($scope) {

Edit: If you're using controllerAs then I think you should rewrite your code:

app.controller('UserController', function() {
  this.user = 'Michael';
}); 
Sign up to request clarification or add additional context in comments.

3 Comments

When I do this I don't get any output.
Oh I just noticed that if I change it to this it works: <div ng-controller="UserController"> {{user}} </div> Can someone explain me why?
@MichaelPittino - I have updated my answer, please check if it helps
1

When you're using the ControllerAs syntax in your HTML, the values that end up getting bound to the controller instance is actually on your this object.

What this means is that your code that attaches user to the scope object is incorrect; instead you should do the following:

app.controller("UserController", function() {
  this.user = "Michael";
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.