Search code examples
angularjsangularjs-ng-initng-init

Angular variable initialized using ng-init is always undefined


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?


Solution

  • 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