gvgvgvijayan gvgvgvijayan - 1 month ago 11
AngularJS Question

Why angular js did not used last assigned value?

<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="angular.js"></script>
</head>
<body ng-app="">
<p>There {{count = 1; (count == 1 ? "is" : "are")}} one of them</p>
<div ng-init="count = 7; unit = 'days'; collection = 'week'">
<p>
There are {{count}} {{unit}} in a {{collection}}.
</p>
</div>
</body>
</html>


Here the
count
is first assigned
1
then again assigned
7
but the result show is like this


There is one of them

There are 1 days in a week.


Why this is happening. Why global scope rule not followed? Last assigned value have to shown!

Answer

Because expression inside {{}} (interpolation) are evaluate on each digest cycle to keep binding in sync with whatever you have in respective models. And count = 1 expression got evaluate several times whenever digest cycle gets kicks off, thus you see 7 values.

Bottom line is don't use {{}} to do assignment to variables. Always to declaration of variable inside controller. ng-init is also not got Idea and best to initialize variable do it inside controller itself.

Comments