Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KO.Computed equivalent in Angular / Breeze Initializer

Trying to get a more in-depth understanding of how Angular treats data binding and understanding it better and one thing is difficult to get my head around -

In Knockout I use a computed to keep track of changes to a property. In Angular it to move this logic into the view, which is a it trivial to me, but if that is the way to do it I understand.

My question is when I am initializing a new entity with Breeze/Angular how do I create computed-like properties that are notified when changes occur to the entities property?

myEntity.fullName = ko.computed(function () {
    return myEntity.firstName + ' ' + myEntity.LastName;
});

in Angular would the equivalent be

myEntity.fullName = function () {
    return myEntity.firstName + ' ' + myEntity.LastName;
};

And does that properly track the entity?

like image 300
PW Kad Avatar asked Aug 14 '13 02:08

PW Kad


1 Answers

You are correct to simply make it a function. If your entity as shown is added to the $scope, then you would access the property like so:

<span class="fullname">{{ user.fullName() }}</span>

Whenever Angular runs a $digest cycle, it will check for a change to the bound property. In this instance, it means it will call the fullName() function and check to see if the result has changed. If it has, anything that has a $watch attached to that item — including simple binding — will be notified of the change.

One caveat of this technique, however, is to make sure that the operations being performed within your function are relatively fast, and also have no side effects. Bound functions like this will be called many times throughout the application.

If you need to have a more complex function, it would be better to handle that within the controller, and update a property on the object manually when it changes.

like image 86
OverZealous Avatar answered Nov 05 '22 07:11

OverZealous