explainer
explainer

Reputation: 1335

how to setup virtual attributes with angularjs?

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?

Upvotes: 0

Views: 1018

Answers (1)

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

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:

var MedicationCtrl = function($scope) {    
    $scope.medication = {
        dosage : 0.5,
        count : 10,
        total : function() {
            return this.dosage * this.count;
        }
    };
}​

You can simply write:

Total: {{medication.total()}}

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:

var MedicationCtrl = function($scope) {    
    $scope.total = function(medication) {
      return medication.dosage * medication.count;
    };
};

and use this function from a markup like follows:

<ul ng-repeat="m in medications" ng-controller="MedicationCtrl">
    <li>{{m.dosage}} + {{m.count}} = {{total(m)}}</li>
</ul>

And the above code in the jsFiddle: http://jsfiddle.net/4r5g5/3/

Upvotes: 6

Related Questions