0

I am learning AngularJS. Now I am initializing variable using ng-init. But the variable value is always undefined. My code is below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angularjs popup</title>
    <script src="http://localhost:8888/angular/angular-js.min.js"></script>
</head>
<body>
<section ng-app="myApp" ng-controller="MainCtrl" ng-init="quantity=1;cost=5">

</section>
</body>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl',function($scope){
    alert($scope.quantity)
})
</script>
</html>

When I run above code, it is always alerting "undefined" for quantity even if I initialized using ng-init. What is wrong with my code? Can I not initialize like that?

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
  • your `alert` in the controller is being executed before the `ng-init` has fired. – Claies Sep 26 '16 at 15:27
  • 1
    in general, you should *always* initialize variables in your controller; `ng-init` is only [appropriate](https://docs.angularjs.org/api/ng/directive/ngInit#!) in *very specific* cases. – Claies Sep 26 '16 at 15:31
  • Thanks so much everyone. Now I am clear with it. – Wai Yan Hein Sep 26 '16 at 15:32

1 Answers1

1

ng-init in the template is being called after the initialisation of the app. If you were to put {{ quantity }} or {{ cost }} in your template you'd see your values displayed as expected.

May I ask, Why are you using ng-init? If you want to hard-code your values for quantity and cost you'd be better off doing it in your controller. It's worth looking at the angular docs for this, it suggests a similar approach

https://docs.angularjs.org/api/ng/directive/ngInit

SimonB
  • 53
  • 6