How do I evaluate the mathematical expression within a string and assign it to a numerical value in angularJS?
Eg: var value = 10;
var someValue = "Math.min(value * 0.22, 106800)". I need someValue to be a valid integer of 2.2.
Is this something which can be done by angularJS?
One way of doing this would be by injecting 'Math' into your scope and using it in say a controller
$scope.Math = window.Math;
Here's a fiddle: http://jsfiddle.net/bxE79/1/
Use eval.
var value = 10;
var someValue = eval("Math.min(value * 0.22, 106800)");
console.log(someValue);
And it will be printed in console
2.2
Related
I have a simple MVC C# controller with 2 dimention array.
ViewBag.states = new SelectList(db.states, "state_code", "state_zone");
If state_code = "FL", I want to get its state_zone value in the controller
I tried:
int newZone = ViewBag.states["FL"].state_zone
but I get error:
Cannot apply indexing with [] to an expression of type 'System.Web.Mvc.SelectList'
Any ideas?
Since ViewBag.states is dynamic property, you can't use indexer of SelectList against it because state_zone already stored inside Text property:
int newZone = ViewBag.states["FL"].state_zone;
Also this declaration seems possible but may throwing indexing error as described in comment:
var zone = ViewBag.states as SelectList;
int newZone = Convert.ToInt32(zone.Items[0].Text); // error: 'cannot apply indexing with [] to an expression of type 'System.Collections.IEnumerable'
To use SelectList item indexer inside ViewBag object, you need to convert it into SelectList first, then use LINQ methods to reveal its value:
var zone = ViewBag.states as SelectList;
int newZone = Convert.ToInt32(zone.Skip(n).First().Text); // n = any index number
// alternative:
int newZone = Convert.ToInt32(zone.Where(p => p.Value == "[any_value]").First().Text);
Similar issue:
Get a text item from an c# SelectList
Does AngularJS have any function or method similar to eval?
I need to get the value of a previously-defined variable, e.g.:
data.mess_5 = "Hello"
c = 5
x = eval( "data.mess_" + c )
Angularjs is javascript, so you can use eval, assuming your var is on the global scope. However, in this particular case (and most other cases), eval is the wrong tool for the job.
data.mess_5 = "Hello"
c = 5
x = data['mess_' + c]
Check the $parse function (taken from Setting dynamic scope variables in AngularJs - scope.<some_string>)
var the_string = 'life.meaning';
// Get the model
var model = $parse(the_string);
// Assigns a value to it
model.assign($scope, 42);
// Apply it to the scope
$scope.$apply();
console.log($scope.life.meaning); // logs 42
I am building a simple Appgyver mobile app using Angularjs and Coffeescript - I'm a beginner with both of these.
I wish to determine the total cost for a list of up to 20 items stored on the database. However, there may be less than 20 items.
I have attempted to do the calculation with ng-bind, which works perfectly as long as all strings contain values. However, if there are less than 20 pairs (values go up to q20 and p20) then the calculation returns NaN.
I would like to determine the total of all existing values for the list. I have looked at numerous examples on stackoverflow, Angularjs.org and other sites and have experimented with a myriad of alternative methods, however I think I lack the basic understanding of how to make this work. Any help would be appreciated.
This is the code I have used, shortened to 3 pairs instead of 20:
<span ng-bind="client['q1'].price * client['p1'].price + client['q2'].price
* client['p2'].price + client['q3'].price * client['p3'].price"></span>
This is the existing controller:
angular
.module('client')
.controller("ShowController", ($scope, Client, supersonic) ->
$scope.client = 0;
$scope.showSpinner = true
$scope.dataId = undefined
_refreshViewData = ->
Client.find($scope.dataId).then (client) ->
$scope.$apply ->
$scope.client = client
$scope.showSpinner = false
supersonic.ui.views.current.whenVisible ->
_refreshViewData() if $scope.dataId
supersonic.ui.views.current.params.onValue (values) ->
$scope.dataId = values.id
_refreshViewData()
$scope.remove = (id) ->
$scope.showSpinner = true
$scope.client.delete().then ->
supersonic.ui.layers.pop()
)
I think you are overloading (in the linguistic sense, not the coding sense) ng-bind. Doing all of that code in your HTML is messy and is not what it was created for. You would be better off doing the math in your controller, and then referencing it in ng-bind. You have only 3 pairs here, but you say you have 20, and could be more, so do it that way:
<span ng-bind="totalPrice"></span>
And in your controller:
var setTotalPrice = function() {
var ret = 0, i, maxClient = 6, client = $scope.client; // or however else you keep track of them
for (i=1;i<=maxClient;i++) {
if (client['q'+i] && client['q'+i].price && !isNaN(client['q'+i].price) &&
client['p'+i] && client['p'+i].price && !isNaN(client['p'+i].price)) {
ret += (client['q'+i].price * client['p'+i].price);
}
}
$scope.totalPrice = ret;
};
$scope.setTotalPrice = setTotalPrice;
setTotalPrice();
Just call setTotalPrice in your controller whenever you want, or on an ng-click.
Please don't abuse ng-bind for calculations! Instead calculate the values in your controller and bind the resulting value.
Problem with your code is -if any of the values is not a number your result becomes NaN. In the controller function you check for the presence of value and then operate. You may want to check whether the value is non-null as well as a number string and then operate on it.
I have created a rootScope variable like
$rootScope.globalData = data;
$rootScope.globalData.chillerConditions.HeatSource.Value = "ST"; //Default Value
$scope.chillerConditions.HeatSource.Value = 1; //Default Value
where data is my returning value from api. Also create a scope variable which is a object contains a list of items.
$scope.chillerAttributes = data.ObjCandidateListChillerAttributes;
$scope.chillerConditions = data.ObjCandidateListConditions;
On HTML I have:
<select ng-model="chillerConditions.HeatSource.Value" style="width:53%;" ng-options="item.Id as item.Description for item in ValidRatingHeatSource" ng-change="heatSourceChanged()" id="ddRatingHeatSource" class="form-control search-select designComboboxHeight" data-container="body"></select>
Here ValidRatingHeatSource is
$scope.ValidRatingHeatSource = \*list of items*\
On change of Drop Down I have written an function. In that
if($scope.chillerConditions.HeatSource.Value == 2)
{
$rootScope.globalData.chillerConditions.HeatSource.Value = "HW";
}
else
{
$rootScope.globalData.chillerConditions.HeatSource.Value = "ST";
}
Till now was the my current code.
Issue is :
When the above function is called then whenever current $rootScope varible i.e. $rootScope.globalData.chillerConditions.HeatSource.Value is changed to "HW" or "ST" it also changing $scope.chillerConditions.HeatSource.Value to "HW" or "ST".
Why so?
Is there any inbuilt functionality in angularjs?
Please suggest if I am making any mistake? New suggestion are also welcome.
This behavior is the way JavaScript works and has nothing to do with AngularJS. JavaScript is an object-oriented (prototype-based) language where objects are addressed by reference and not by value. E.g. assign car2 to car1 and both of them will reference the same object (JSFiddle)
var car1 = {make: "Audi"}
var car2 = car1;
car2.make = "Toyota";
So in your case, $rootScope.globalData.chillerConditions.HeatSource and $scope.chillerConditions.HeatSource are the same object.
Rather, it seems like you want to create a copy. You can do so with angular.Copy
$scope.chillerAttributes = angular.copy(data.ObjCandidateListChillerAttributes);
$scope.chillerConditions = angular.copy(data.ObjCandidateListConditions);
In your example u have both ng-model and ng-change, so:
1. User change value in select.
2. $scope.chillerConditions.HeatSource.Value changes (ng-model)
3. heatSourceChanged starts (ng-change) -> $rootScope.globalData.chillerConditions.HeatSource.Value changes
So everything works as should...
How can we convert an integer to string in AngularJs, like parseInt() converts string to int.
I tried wit $parse, which itself is a wrong approach I think..
.toString() is available, or just add "" to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
var x : number = 3;
var st : string = String(x);
console.log(st);