Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular controller variable changes when set afterwards?

var jem = 55;

var app = angular.module("store",[]);
app.controller("storeController",function(){
  this.product = jem;
});


jem = 0;
<!DOCTYPE html>
<html ng-app="store">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="storeController as store">
  <p>{{"HI"}}</p>
  <p>{{store.product}} </p>

</body>
</html>

Why does this output is "0" instead of "55"? Since jem is a basic javascript variable when product is assigned with jem it gets its value copied and should not change when jem is changed?

like image 304
Johnny Chen Avatar asked Aug 16 '26 09:08

Johnny Chen


1 Answers

Notice that your controller definition is inside a callback function (as it should be...)

app.controller("storeController", function(){
  this.product = jem;
});

A side effect of this, relevant to your question, is that the assignment statement within the callback, this.product = jem, will get executed after the assignment statement, jem = 0, outside of the callback.

The takeaway is that callbacks do not take place sequentially with the rest of your code.

like image 132
sfletche Avatar answered Aug 17 '26 23:08

sfletche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!