0

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.

4 Answers 4

3

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

this.test = 'Whatever';
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly fine with the detailed reason. Thank you!
2

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

Comments

2

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

2 Comments

In his example he want's to avoid use of $scope, that's why uses controller as syntax.
ahh! yes I didn't notice that, any way thanks @Raulucco :)
1

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

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.