Reputation:
I am using the following function in my app controller:
this.state = {
net: false,
netd: false,
network: function (active) {
if (active) {
this.state.net = true;
t = window.setTimeout(function () {
this.state.netd = true;
}.bind(this), 500);
} else {
window.clearTimeout(t);
this.state.net = false;
this.state.netd = false;
}
}.bind(this)
};
In my child controller I call it like this:
app.state.network(true);
Then after some time:
app.state.network(false);
In my child HTML I view the net and netd like this:
xx {{ app.state.net }} yy
xx {{ app.state.netd }} yy
The network function is called as expected and I can see xx {{ app.state.net }} yy
change from false > true but xx {{ app.state.netd }} yy
is always false even though the debugger shows it gets to be set as true here: this.state.netd = true;
Can anyone tell me why the state of netd does not seem to change in my browser ?
Upvotes: 1
Views: 185
Reputation: 49714
You don't want to use setTimeout()
with AngularJS (generally speaking) as it executes "outside" of angular.
Instead of using setTimeout
window.setTimeout(function () {
this.state.netd = true;
}, 500);
Use the angular $timeout
service
$timeout(function() {
this.state.netd = true;
}, 500);
Upvotes: 0
Reputation: 691755
You're using the window.setTimeout()
function, which changes the object without angularJS being aware of it. Use the $timeout
service, which exists exactly to not have this problem, or manually call $scope.$apply()
every time you change a value as a result of an event that is not coming from angular.
Upvotes: 2