Does AngularJS have a function like eval? - angularjs

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

Related

Laravel compare two array

I have to arrays and I have to find difference values from it.
Here is my Laravel Controller code
$product_list = Operation::where('kvit_id', $kvit->id)->pluck('product_id')->toArray();
$hamkor_products = ListProduct::where('user_id', $newkvit->user_id)->pluck('product_id')->toArray();
$operProductList = array_diff($product_list, $hamkor_products);
dd($product_list, $hamkor_products, $operProductList);
Here is result which I'm getting
What kind of mistake I made? $operProductList is returns []
You must just change the order of parameters in array_diff(), it must be like :
$product_list = Operation::where('kvit_id', $kvit->id)->pluck('product_id')->toArray();
$hamkor_products = ListProduct::where('user_id', $newkvit->user_id)->pluck('product_id')->toArray();
$operProductList = array_diff($hamkor_products, $product_list);
dd($product_list, $hamkor_products, $operProductList);

$timeout cannot find my variable

Ok using Angular and Coffeescript here the following works:
angular.module 'someApp'
.factory 'someFactory', ($timeout) -> new class SomeClass
constructor: ->
#humans = 1
findHuman: ->
$timeout((=>#humans+=1), 1000)
Which is fine I guess but I'd like to have the #humans+=1 part somewhere else.
So why does this not work?
angular.module 'someApp'
.factory 'someFactory', ($timeout) -> new class SomeClass
constructor: ->
#humans = 1
findHuman: ->
$timeout(addOneHuman, 1000)
addOneHuman = =>
#humans+=1
Testing around with console.log or $log, adding #'s here and there, -> instead of => sometimes the variable humans is NaN, sometimes it is undefined.
What do I have to do to make this work? :)
I don't know the Angular side of things that well but I think your problem is that this:
addOneHuman = =>
doesn't do what you think it does. Something like this:
class C
f = ->
m: ->
creates f as essentially a private function within C. The JavaScript version is equivalent to:
var C = (function() {
function C() {}
var f = function() {};
C.prototype.m = function() {};
return C;
})();
so f is just a variable that references a function and f is in scope for anything in C. Changing it to:
f = =>
doesn't do anything because there is no this that applies when f is defined. On the other hand, m is a method (note the C.prototype.m in the JavaScript version) so there is an applicable this and m: => can do something useful.
You just want your addOneHuman to be a method rather than a plain old function:
addOneHuman: =>
# ---------^
There might be something useful to you in a couple of my other answers:
coffeescript scope of variable assignment vs property assignment in object's other properties
How to make method private and inherit it in Coffeescript?

Can't sum values in Angularjs if one value is an empty string

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.

rootScope is upating on scope variable update

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...

Calculate mathematical expression within string in angularJS

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

Resources