Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular, what ways can you auto-update a data binding that is bound to a method?

Say you have an object with a method:

/*
chat.author    ==  a String
chat.message   ==  a String
chat.timestamp ==  a Date 
chat.timeago() ==  a method that returns a string, like "2 minutes ago"
*/

And your html looks something like:

<div>{{ chat.author    }}</div>
<div>{{ chat.message   }}</div>
<div>{{ chat.timeago() }}</div>

The return value of chat.timeago() will change based on the elapsed time since chat.timestamp, so it may change from "just now", to "a few seconds ago", to "a minute ago", "2 hours ago", etc.

What options exist to instruct Angular when to update the data that is bound to the method, and which option is the most elegant or traditional way in Angular?

like image 702
paulwal222 Avatar asked Nov 19 '25 21:11

paulwal222


1 Answers

You should bind to variable form scope and update this variable using the $timeout function.

Angular can refresh view state only when some conditions occurred (callback executed, AJAX received, $scope updated, ...), so you can't bind to function and expect that it refresh automatically

like image 88
suvroc Avatar answered Nov 21 '25 11:11

suvroc