angular js not storing records in value field - angularjs

<div ng-init="value = (total_rec - ans_rate)">
<h4 ng-if="value<0">0</h4>
<h4 ng-if="value>=0">{{total_rec - ans_rate}}</h4>
</div>
I want to print 0 if result of total_rec - ans_rate comes 0 or less than 0, here total_rec & ans_rate is variables defined in angular file. please suggest me answers.
i want to implement this logic here
ex.
var x= total_rec-ans_rate ;
if (x <=0){
print 0;
}else{
print x;
}
but in this way :-
<div ng-init="value = (total_rec - ans_rate)">
<h4 ng-if="value<0">0</h4>
<h4 ng-if="value>=0">{{total_rec - ans_rate}}</h4>
</div>
please suggest me the proper way to do this.. Thanks..

Hope this make clear to you.
<body ng-controller="MainCtrl">
<div ng-init="value = cal_result()">
<h4 ng-if="value < 0">0</h4>
<h4 ng-if="value > 0">{{value}}</h4>
</div>
<script>
var app = angular.module('demoApp', []);
app.controller('MainCtrl', function($scope) {
$scope.total_rec =0;
$scope.ans_rate = 3;
$scope.cal_result = function () {
return $scope.total_rec - $scope.ans_rate;
}
});
</script>

Related

How to add the values which is present inside the array (or) Json?

I been wondering if someone fixed my issue. my code looks like this.
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope){
//Adding New Check# and Check amount Text Boxes
$scope.checks = [{checkNum1: '',checkAmt1:''}];
$scope.add = function() {
var newCheckNo = $scope.checks.length+1;
$scope.checks.push({['checkAmt'+newCheckNo]:''});
};
$scope.tot = function() {
return $scope.checks;
};
$scope.total = function() {
var value = "";
for(var i =0 ; i<=$scope.checks.length;i++ ){
value += $scope.checks.get('checkAmt1');
}
return value;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-md-12">
<div class="col-md-6">
<div ng-repeat="check in checks">
<div class="form-group">
<label>check Amount:</label>
<div class="col-md-5">
<input type="text" class="form-control" id="{{'id'+($index+1)}}" ng-model="check['checkAmt'+($index+1)]" maxlength="6" />
</div>
</div>
</div>
<button type="button"
ng-click="add()">Add More</button>
</div>
</div>
<div class="col-md-6">
<!--<p ng-repeat="check in checks">{{check['checkAmt'+($index+1)]}}</p>-->
</div>
<label>{{tot()}}</label>
<label>{{total()}}</label>
</div>
I am initializing $scope.checks = [{checkAmt1:''}];
and pushing the additional values on clicking Add Button (checkAmt2,checkAmt3,...so on). i want to add those values(checkAmt1+checkAmt2+...so on) dynamically by using {{total()}}. total() function is calling, i know logic inside the for loop is wrong. Please help me to fix the logic (or) Suggest me if any other way to add those values.
Thanks in advance.
Note: please refer the result in full page view.
first of all, it is not a proper way of using an array.
You can sum up column with same name and not dynamic name.
I think to make the entries distinct you have used in such manner. But it is not the good way and will make your operation on array complicated.
You can try to construct array in following way,
$scope.checks = [{id:'',checkNum: '',checkAmt:''}];
The complete changed code will look like
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope){
//Adding New Check# and Check amount Text Boxes
$scope.checks = [{id:'', checkAmt:''}];
$scope.add = function() {
var newCheckNo = $scope.checks.length+1;
$scope.checks.push({'id':newCheckNo ,'checkAmt':''});
};
$scope.tot = function() {
return $scope.checks;
};
$scope.total = function() {
var value = 0;
for(var i =0 ; i<$scope.checks.length;i++ ){
value += parseInt( $scope.checks[i].checkAmt);
}
return value;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-md-12">
<div class="col-md-6">
<div ng-repeat="check in checks">
<div class="form-group">
<label>check Amount:</label>
<div class="col-md-5">
<input type="text" class="form-control" id="{{'id'+($index+1)}}" ng-model="check['checkAmt']" maxlength="6" />
</div>
</div>
</div>
<button type="button"
ng-click="add()">Add More</button>
</div>
</div>
<div class="col-md-6">
<!--<p ng-repeat="check in checks">{{check['checkAmt']}}</p>-->
</div>
<label>{{tot()}}</label>
<label>{{total()}}</label>
</div>
I'm not sure why indeed you push into the array such objects, and not just numbers, but as you iterate over it - you can just access each value by index, then take the correct object's value:
for(var i =0 ; i<=$scope.checks.length;i++ ){
value += $scope.checks[i]['checkAmt' + i];
}

changing variables on click in angular

What I am looking for is more of a toggle i suppose. basically I have this:
<i class="checkbox pull-left" ng-click="changePrice()"></i>
I have a variable in my controller like so:
$scope.basePrice = 10;
What i am looking to do, is on checking the box, switch the variable to a different number. Which I can do. My problem lies when i uncheck the box, and the variable doesnt switch back. I have tried an if/else if statement, ng-change, ng-click, i was thinking switch might work, but at this point, im clueless. Any help would be appreciated.
requested controller example:
app.controller('examplectrl', '[$scope', function($scope){
$scope.basePrice = 10;
$scope.changePrice = function(){
if($('#changePrice.checked')){
console.log("checked");
}else{
console.log("not checked.")
}
};
}]);
I added a second variable that keep the toggle value as a boolean
The price is updated to 25 but you can add your own code there
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.basePrice = 10;
$scope.priceToggle = false;
$scope.changePrice = function() {
$scope.priceToggle ? $scope.basePrice = 10: $scope.basePrice = 25;
$scope.priceToggle = !$scope.priceToggle;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<button class="checkbox pull-left" ng-click="changePrice()">Change price</button>
<p ng-bind="basePrice"></p>
</body>
You can do it without using a controller function:
angular.module('app', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<i ng-init="basePrice = 10" class="checkbox pull-left" ng-click="basePrice = basePrice == 10 ? 25 : 10">PRICE</i>
{{basePrice}}
</body>

sum of values in a list using angular way

I have a short piece of sample here where myself trying to get total of values in angular way as,
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total = 0">
<ul>
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">, Total - {{total = total+x.val}}</span>
</li>
</ul>
</div>
But total is incorrect. How can it be achieved?
EDIT: Myself trying to get total within the ng-repeat loop beside last element. There is an accepted answer in this question and below answer also work in same logic. But In that method, the function getTotal() will call myarr.length times and each time the array loops in controller right? So as per example in the question, array will loop completely 6 times (myarr.length + once in ng-repeat ie, 5+1). Do i wrong?
Try this method, no function used in controller , using ng-init in ng-repeat
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total=0">
<ul >
<li ng-repeat="x in myarr" ng-init="$parent.total = $parent.total + (x.val)"> {{x.val}}
<span ng-if="$last">{{total}}</span>
</li>
</ul>
</div>
Another method ,
Use array.reduce to add sum of array Link
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
$scope.addTotal = function(){
var sum = $scope.myarr.reduce($scope.add);
return sum.val;
}
$scope.add = function(a,b){
return {val:a.val + b.val};
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total=0">
<ul >
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">{{addTotal()}}</span>
</li>
</ul>
</div>
Try doing all calculations in angular controller itself and storing it in varaible. But if you are worried about values in array constantly changing you can also use a calcTotal function in your controller. Also ng-repeat should be on li and not ul.
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total = 0">
<ul >
<li ng-repeat="x in myarr"> {{x.val}}
<span ng-if="$last">, Total - {{getTotal()}} or {{totalValue}}</span>
</li>
</ul>
</div>
Your controller will be like
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
//first approach
$scope.totalValue = 0;
for(i=0;i<$scope.myarr.length;i++){
if($scope.myarr[i] && $scope.myarr[i].val)
$scope.totalValue+=$scope.myarr[i].val;
}
//OR
//second approach
$scope.getTotal = function(){
var total = 0;
for(i=0;i<$scope.myarr.length;i++){
if($scope.myarr[i] && $scope.myarr[i].val)
total+=$scope.myarr[i].val;
}
return total;
}
});
If you are using variable approach, you will have to explicitly calculate $scope.getTotal everytime the array values change. By the function approach it will happen itself, but binding functions on UI is little expensive as they keep re-calculating on every digest cycle.
You can use angular.forEach to loop and have you total count.
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.total = 0;
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
angular.forEach($scope.myarr, function(value){$scope.total+=value.val});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl">
<ul >
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">{{total}}</span>
</li>
</ul>
</div>

store math operation in a angularjs variable

var app = angular.module('App', []);
app.controller('Ctrl', function($scope, $http){
$scope.plusvalenza1='';
$scope.budget0=60;
$scope.plusvalenza= function(venduto,acquistato){return venduto - acquistato};
$http.get("rosa.php").success(function(data){
$scope.rose=data;
});
$http.get("giocatoriLiberi.php").success(function(data){
$scope.giocLiberi=data;
});
$scope.range = function(start, end) {
var result = [];
start = parseInt(start); //Make string input int
end = parseInt(end);
for (var i = start; i <= end; i++) {
result.push(i);
}
return result;
};
<div ng-controller="Ctrl">
<div class="row">
<div class="col-md-3">
<label>Vendere:</label>
<select ng-model="selectedItem1" ng-options="(rosa.nome+' '+rosa.costo) for rosa in rose"></select>
</div>
<div class="col-md-3">
<label>Acquistare:</label>
<select ng-model="giocAcq1" ng-options="(lib.nome+' '+lib.costo) for lib in giocLiberi | filter:{ruolo:selectedItem1.ruolo}"></select>
</div>
<div class="col-md-1">
<label>Offerta:</label>
<select ng-model="off0" style="width: 60px" ng-options="page for page in range(giocAcq1.costo, budget0--selectedItem1.costo)" ></select>
</div>
<div class="col-md-3">
<label></label>
<div ng-model="budget0">Il tuo budget e': {{budget0}} fantamilioni</div>
<p ng-model="plusvalenza1" ng-show="selectedItem1.costo > giocAcq1.costo">Questa offerta ti garantisce una plusvalenza di {{plusvalenza(selectedItem1.costo,giocAcq1.costo)}} fantamilioni per la prossima busta</p>
</div>
</div>
</div>
in the attached code i'd like to store the result of the plusvalenza(selectedItem1.costo,giocAcq1.costo) function in the ng-model="plusvalenza1" or in any way in a variable thath i can after use in a post service to send data at my db.
I tried like a select tag but i have not the same result...can anyone help me?
thanks in advance...
Why don't you save the result in the scope before returning it?
Like this:
$scope.plusvalenzaResult = 0;
$scope.budget0 = 60;
$scope.plusvalenza = function(venduto, acquistato) {
$scope.plusvalenzaResult = venduto - acquistato;
return $scope.plusvalenzaResult;
//or you can just reference this variable in html instead of returning it
};

AngularJS show 2 random records

I just started up learning AngularJS and I have no idea how to solve this problem. For example I have 4 records (car, plane, ship, train) and I only want to show 2 randomly in ng-repeat.
Examples:
1.st. plane, ship
2.nd. car, train
3.rd. train, plane
So how would syntax look like ?
JS:
app.controller('WorkCtrl', function($scope, $http) {
$http.get('work.json').success(function(work) {
$scope.work = work;
});
});
HTML:
<div class="work" ng-controller="WorkCtrl">
<ul class="grid">
<li ng-repeat="work in work">
<a href="#{{ work.link }}" target="blank_">
<div class="background"></div>
<h3 class="name">#{{ work.name }}</h3>
<p class="description">#{{ work.description }}</p>
<img ng-src="#{{ work.image_path }}">
</a>
</li>
</ul>
</div>
I created something like this:
var app = angular.module("myApp", []);
app.controller('myCtrl', ['$scope', function($scope){
$scope.records = ['plane', 'train', 'car', 'submarine'];
}]);
app.filter('randomSelection', function(){
return function(inputArray, numItemsToReturn){
// assuming you pass an array, not doing checking here
if(!inputArray)
return inputArray;
var numItems = inputArray.length;
var min = 0;
var max = numItems-1;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
while (inputArray.length > numItemsToReturn){
inputArray.splice(random, 1);
}
return inputArray;
};
});
HTML:
<div ng-repeat="record in records | randomSelection : 2">
{{record}}
</div>
Seems to work, no infdigest loop. You may want to add another condition in the while loop to break out so as to avoid an infinite loop.
http://embed.plnkr.co/mJ5Q7n24uLnELSNPUB9z/script.js
<div ng-repeat="w in work = (work|orderBy:randomize).slice(0, 2)">
$scope.randomize = function () {
return 0.5 - Math.random();
};
Demo: http://jsfiddle.net/hmx2zqex/

Resources