Sam Mason
Sam Mason

Reputation: 1037

Perform calculation on ngModel value from input and then show calculated value

I have a simple angular app that has an ng-model attached to an input that takes a width

<input type="text" placeholder="1280" ng-model="containerWidth">

I'm then showing the containerWidth value in a binding in the template further down the page {{containerWidth}}

I would like to perform a simple calculation on the value that is typed into the input e.g simply adding 20 to the number.

I have tried adding {{containerWidth + 20}} but it does not have the desired effect as it just concats the strings of numbers.

Upvotes: 0

Views: 4169

Answers (3)

AlphaG33k
AlphaG33k

Reputation: 1678

In order to add an int to your input fields value, you will need to turn the string value that you are entering into the field into an integer using parseInt() (native js method). This is also a possible duplicate of AngularJS how to add numbers inside the expression from a textbox?

Here, the solution was to add the native JS parseInt into the scope to be used like this:

Inside controller:

$scope.parseInt = parseInt;

In view/DOM:

<input type="text" value="{{ parseInt(num1) + 1 }}" />

Here is the script:

"use strict";
var demo = angular.module('demo',[]);

demo.controller('demo-controller', function($scope){
  $scope.parseInt = function(s){
   return parseInt(s, 10);
  };
});

Here is an interactive demo to support this solution:

http://codepen.io/nicholasabrams/pen/zGPWQx

Hope this helps!

Upvotes: 1

floor
floor

Reputation: 1572

You can use parseInt. Although I support just changing the html to a number format. Here is how you would use parse int:

First in your controller you make:

 $scope.parseInt = parseInt;

This puts the parseInt function into the scope so you can use it in an expression.

Then you can write your expression like this:

{{parseInt(containerWidth) + 20}}

Upvotes: 0

michelem
michelem

Reputation: 14590

Just change the input type to number:

<input type="number" placeholder="1280" ng-model="containerWidth">

JSFiddle

Upvotes: 0

Related Questions