1

Say I have a model in angular, with three variables in my model, say a,b,c, and I want to have c=a*b.

I've done it by adding a function, updateC(), that updates c, and then my HTML would look like this:

<input name="a" ng-model="a" ng-change="updateC()"></input>
<input name="b" ng-model="b" ng-change="updateC()"></input>
<input name="c" ng-model="c" readonly></input>

But that's not a nice solution if I have alot of such triplets, because I need to define a function for each such triplet. Is there a way to bind the value of the element in the model to some formula? I.e. is there some attribute ng-like-bind-but-updates-model such that the following html will work:

<input name="a" ng-model="a"></input>
<input name="b" ng-model="b"></input>
<input name="c" ng-model="c" ng-like-bind-but-updates-model="a*b" readonly></input>
3
  • 1
    Have you tried value and the {{...}} binding instead of ng-model? I.e. <input name="c" value="{{ a*b }}" readonly />. Commented Nov 23, 2015 at 10:10
  • you can just use <input name="c" ng-model="a * b" readonly></input> Commented Nov 23, 2015 at 10:11
  • Both won't work: jsfiddle.net/1j5grwhy @yarons the idea is to have a model that has a variable named c with the right value. Commented Nov 23, 2015 at 10:17

3 Answers 3

2

This seems to work, not sure if that's what you want to achieve:

<input name="a" ng-model="a"></input>
<input name="b" ng-model="b"></input>
<input name="c" value="{{c=a*b}}" readonly></input>
Sign up to request clarification or add additional context in comments.

Comments

1

Here's a nice trick that solves your problem:

<input name="c" ng-model="c = a * b" readonly />

demo

Comments

0

you can simply bind the value of input C

<input name="c" value="{{c=a*b}}"></input>
<label>{{c}}</label>

like this: http://codepen.io/Visualife/pen/xwNKjj

you'll need to handle initial values though for a & b.

4 Comments

You mean with ng-bind?
no, with value, please see the codepen I've attached mate
Sorry, commented before You've added the codepen. I want to have a variable named c in my scope, and your solution is essentially the same as using ng-bind, it won't update c inside the scope itself.
then you can set c inside 'value' as per the update and updated pen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.