I come from a Rails background and am attempting to use AngularJS with Rails. I am stuck on a very simple thing: how does one construct what rails calls ‘virtual attributes’ in an Angularjs environment? Let me give an example.
I have a rails model, called Medication, and it has two attributes, dosage and count. I want to have a ‘total’ virtual attribute that returns dosage * count. This is trivial in Rails, since it is just an instance method of class Medication.
So, how does that map into the AngularJS world?
Clarification: I am using an ng-repeat directive on Medications (plural) for which I have a MedicationsController. For each ng-repeat loop, I get a ‘medication‘ object, where I want to apply this ‘instance method’
total = function() { return dosage * count }
How is that coded? Where do I put the function?
It is really simple with AngularJS as you can use any JavaScript function in AngularJS view. So just define a function on your object (or directly on a scope). For example, give a controller like this:
You can simply write:
Here is a jsFiddle: http://jsfiddle.net/4r5g5/1/
Then, if you’ve got a collection of items and don’t want to put any logic on an object level, you can define this method on a controller like so:
and use this function from a markup like follows:
And the above code in the jsFiddle: http://jsfiddle.net/4r5g5/3/