AngularJS - Controller value not dispaying

I'm using AngularJS 1.5.0

Here's my HTML:

<!DOCTYPE html>
<html ng-app="app">
  <head>
  </head>

  <body ng-controller="TestController as controller">

    {{controller.test}}

    <script src="libraries/angular/angular.min.js"></script>
    <script src="js/app.js"></script>
  </body>

</html>

Here's my app.js:

var app = angular.module("app", []);

app.controller("TestController", function() {
  var test = "Hello World";

//  window.alert(test); THIS ALERT IS WORKING
});

In my index, it doesn't display anything. However, alerting the test variable does work.

Upvotes: 0

Views: 58

Answers (4)

gaurav bhavsar
gaurav bhavsar

Reputation: 2043

You have to use $scope to bind value in html code.

app.controller("TestController", function($scope) {
  $scope.test = "Hello World";
});

or you can use this to create current controller's instance

app.controller("TestController", function($scope) {
  this.test = "Hello World";
});

Upvotes: 2

Andrew
Andrew

Reputation: 1534

IF you want to display a value from controller itself you should assign it to controller using this keyword: this.test = "your value here". If you want to use controllers' scope so do $scope.test = "value here" and in view use it with {{test}}.

When you declaring your variable with var keyword it will be private, but to use it it view you need it to be a public

Upvotes: 1

Raulucco
Raulucco

Reputation: 3426

The test variable is private to your controller. Assign it to the controller instance:

this.test = 'Whatever';

Upvotes: 3

murli2308
murli2308

Reputation: 3002

Assign value to $scope

var app = angular.module("app", []);

app.controller("TestController", function($scope) {
   $scope.test = "Hello World";

 //  window.alert(test); THIS ALERT IS WORKING
});

or you can also use the other way

var app = angular.module("app", []);

app.controller("TestController", function($scope) {
   this.test = "Hello World";

 //  window.alert(test); THIS ALERT IS WORKING
});

Upvotes: 2

Related Questions