AngularJS - Dynamically Change Variable based on Another Variable - angularjs

I'm trying to figure out how to use a set of if-else statements to dynamically change a value in the DOM using Angular JS.
The value I want to change is basketballpayout.basketballpay based on what the value of the team's total salary is (payout.grossprod)
Here's the code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body ng-app="Payout">
<form novalidate ng-controller="PayoutCtrl">
ENTER YOUR TEAM'S TOTAL SALARY <input type="text" name="Gross Production" placeholder="$" ng-model="payout.grossprod"><br />
ENTER YOUR CURRENT TEAM'S NET PAYOUT ACCOUNT <input type="text" name="Net Payout" placeholder="%" ng-model="payout.currentpay"><br />
<p >Current Payout: {{payout.currentpay}} %</p>
<p>Current Yearly Compensation: {{payout.grossprod * payout.currentpay / 100 | currency }}</p><br />
<p>basketball Payout: {{basketballpayout.basketballpay}} %</p>
</form>
var app = angular.module("Payout",[]);
app.controller("PayoutCtrl", function($scope) {
$scope.payout= {currentpay: 0, grossprod: 0};
$scope.basketballpayout= {basketballpay: "", basketballcom: 0, basketballdif: 0};
if ($scope.payout.grossprod === 0){
$scope.basketballpayout.basketballpay="0";
percent = 0;
} else if ($scope.payout.grossprod < 175000){
$scope.basketballpayout.basketballpay="20";
percent = 0.20;
} else if ($scope.payout.grossprod < 200000){
$scope.basketballpayout.basketballpay="25";
percent = 0.25;
} else {
$scope.basketballpayout.basketballpay="60";
percent = 0.60;
}
});

Just set the view binding to a function call rather than a property and have that function do the needed calculation.
Live Demo
<p>{{ foo() }}</p>
JS:
$scope.foo = function() {
//calculate and return the desired binding
return $scope.bar * $scope.baz;
};
The other problem you're having is that you're comparing strings as though they are numbers. You should use type="number" or you can use myNumber = parseInt($scope.myProp, 10) to get a number rather than a string.

This is a sample of how one select input is dependent on another select input.
<md-select name="inputName" ng-model="inputModel"
ng-change="anotherInputModel = (inputModel == 'Some Value') ? 'value of anotherInputModel' : (inputModel == 'Some other value') ? Some Another Value : ''>
<md-option ng-value="val.value" ng-repeat="val in val">
{{val.value}}
</md-option>
</md-select>
<md-select name="anotherInput" ng-model="anotherInputModel">
<md-option ng-value="value.value" ng-repeat="value in Values">
{{value.name}}
</md-option>
</md-select>

Related

How to set default select value in AngularJS?

I am totally new to Angular Js 1.0 and I am struggling in one of the simple code here. I wanted to show the default selected value in my dropdown. Below is the code I have used
<select id="ddlHeritage" class="form-control" columnname="HeritageIssues"
ng-change="riskCltr.showriskcomment()"
ng-focus-compliance="" ng-model-options="{'updateOn':'default blur', 'debounce':{'default': 250, 'blur':0}}" ng-model="McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues">
<option ng-repeat="item in (ValuerList = (McProMainCtrl.mcProEntry.McPro_DropDownData | orderBy:'Name' | filter:{GroupID:'120'} )) "
ng-selected="{{item.Value==McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues}}" value="{{::item.Value}}">
{{::item.Name}}
</option>
</select>
In the above code I am getting dropdown value from database(including the "--Select--" value)
However, I have null values under the field McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues.
I wanted to select value --Select-- when McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues value is null. I am actually struggling as to how to accomplish it in angularjs
When I add the below line above Option it add two "Select"
<option value="null">--Select--</option>
Any help is appreciated.
Try adding value="null" in your select element :
<select id="ddlHeritage" value="null" class="form-control" columnname="HeritageIssues"
ng-change="riskCltr.showriskcomment()"
ng-focus-compliance="" ng-model-options="{'updateOn':'default blur', 'debounce':{'default': 250, 'blur':0}}" ng-model="McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues">
<option ng-repeat="item in (ValuerList = (McProMainCtrl.mcProEntry.McPro_DropDownData | orderBy:'Name' | filter:{GroupID:'120'} )) "
ng-selected="{{item.Value==McProMainCtrl.mcProEntry.McPro_Risk.HeritageIssues}}" value="{{::item.Value}}">
{{::item.Name}}
</option>
</select>
This is similar things I have solve in my project. No need any option
var app = angular.module('angularjs-starter', []);
app.controller("unitController", function ($scope) {
$scope.units = [{name: "Crore", value: "Crore"},
{name: "Lakh", value: "Lakh"},
{name: "INR", value: "INR"},
{name: "--------", value: "", separator: true},
{name: "Million", value: "Million"}];
$scope.financialDataUnit = "Crore";
});
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller='unitController'>
<select ng-model="financialDataUnit"
ng-options="unit.value as unit.name disable when unit.separator for unit in units">
</select>
</body>
</html>

Second select box needs to be populated after the first select box is selected

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<style>
.margins{
margin-right:8px;
margin-bottom: 5px;
}
</style>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<h2>LogValues</h2>
<div class="logval" ng-repeat="num in loop">
<select class="margins" ng-change=populate() class="custom-select"
id="inputGroupSelect01" ng-model="logType"
ng-options="x.type for x in logValues[0].parameters">
<option value="" disabled selected>Select Log Values</option>
</select>
<select class="margins" ng-model="logVal"
ng-options="y.val for y in statistics">
<option value="" disabled selected>Select Statistic</option>
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.loop = [1,2,3,4];
$scope.logValues =
[
{
"name" : "Log Values",
"parameters" :
[
{"type":"Depth Curve"},{"type":"Conductivity Attenuation -Corr- 400kHz BHI_LWD"},{"type":"Conductivity [CACLMED]"},{"type":"DeepResistivity[RACLMED]"},
{"type":"DeltaTCompressionalBHI_LWD"},{"type":"Sonic Compressional [DTCED]"},{"type":"Gamma Ray - Apparent BHI_LWD"},{"type":"Gamma Ray [GRAMED]"},
{"type":"Medium Resistivity [RPCLMED]"},{"type":"Resistivity Attenuation -Corr- 2MHz BHI_LWD"}
]
}];
$scope.statistics = []
$scope.populate = function() {
$scope.statistics = [
{"val":"None"},{"val":"Mean"},{"val":"Median"},{"val":"Mode"},{"val":"Std Deviation"},{"val":"Variance"},
{"val":"Mix "},{"val":"Max"}
]
}
});
</script>
</body>
</html>
The Above code is printing the two select boxes four times.The requirement is to not show any option in second select box before the user selects the first select box.I have achieved it by emptying the statistics array initially and populating it using on change function.
The problem is that when I select an option in first select box in row1 the respective 'select statistic' is getting populated which is fine but along with it the remaining 'select statistic' select boxes are also getting populated.I need it to be empty until i select the respective row select box.The explanation may be confusing please check the demo for better understanding. Thanks in Advance!Please help..
I have included the Demo
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<style>
.margins{
margin-right:8px;
margin-bottom: 5px;
}
</style>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<h2>LogValues</h2>
<div class="logval" ng-repeat="num in loop">
<select class="margins" id="inputGroupSelect01"
ng-model="num.logType"
ng-options="x.type for x in logValues[0].parameters">
<option value="" disabled selected>Select Log Values</option>
</select>
<select class="margins" ng-disabled="!num.logType"
ng-model="logVal"
ng-options="y.val for y in statistics">
<option value="" selected>Select Statistic</option>
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.loop = [{"stat":1},{"stat":2},{"stat":3},{"stat":4}];
$scope.logValues =
[
{
"name" : "Log Values",
"parameters" :
[
{"type":"Depth Curve"},{"type":"Conductivity Attenuation -Corr- 400kHz BHI_LWD"},{"type":"Conductivity [CACLMED]"},{"type":"DeepResistivity[RACLMED]"},
{"type":"DeltaTCompressionalBHI_LWD"},{"type":"Sonic Compressional [DTCED]"},{"type":"Gamma Ray - Apparent BHI_LWD"},{"type":"Gamma Ray [GRAMED]"},
{"type":"Medium Resistivity [RPCLMED]"},{"type":"Resistivity Attenuation -Corr- 2MHz BHI_LWD"}
]
}];
// $scope.statistics = []
// $scope.populate = function() {
$scope.statistics = [
{"val":"None"},{"val":"Mean"},{"val":"Median"},{"val":"Mode"},{"val":"Std Deviation"},{"val":"Variance"},
{"val":"Mix "},{"val":"Max"}
]
//}
});
</script>
</body>
</html>
First you must loop on objects instead of numbers in $scope.loop in order to generate different scope for each select model, one value for each ng-model and then you can disable the second select box depending on the value of the first select box. Here I have disabled the second select box if the first select box model is undefined.. It will be enabled once you pick up a log value

Add or Remove selected elements from multi select box using angular js

I want to display one dynamic table, But table columns I want to select at run time. For that purpose I have taken two multi select box, in first Multi select am loading all column names using Json.
Now my requirement is, I want add selected column names from first multi select box to second multi select box. And if required I also want to remove from second multi select box.
I have taken two buttons, one for adding and other for removing.
Can any one help me with this requirement. How can I do it using AngularJs?
please refer attached image to clear with my requirement.
Thank in advance..
angular.module('app', []).controller('MoveCtrl', function($scope) {
$scope.available = [];
$scope.selected = [];
$scope.moveItem = function(items, from, to) {
angular.forEach(items, function(item) {
var idx = from.indexOf(item);
from.splice(idx, 1);
to.push(item);
});
// clear selection
$scope.available = "";
$scope.selected = "";
};
$scope.moveAll = function(from, to) {
angular.forEach(from, function(item) {
to.push(item);
});
from.length = 0;
};
$scope.selectedclients = [];
$scope.availableclients = [{
id: 1,
name: 'Bob'
}, {
id: 2,
name: 'Sarah'
}, {
id: 3,
name: 'Wayne'
}, {
id: 4,
name: 'Pam'
}];
});
input {
display: block;
margin: 0 auto;
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.2.17" data-semver="1.2.17" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body ng-controller="MoveCtrl">
<h1>Move items between Select boxes</h1>
<div style="float:left">
<div>Available Clients</div>
<div>
<select size="5" multiple ng-model="available" ng-options="client as client.name for client in availableclients" style="width: 100px;height:100px"></select>
</div>
</div>
<div style="float:left; width: 100px; text-align:center">
<div> </div>
<input id="moveright" type="button" value=">" ng-click="moveItem(available, availableclients,selectedclients)" />
<input id="moverightall" type="button" value=">>" ng-click="moveAll(availableclients,selectedclients)" />
<input id="move left" type="button" value="<" ng-click="moveItem(selected, selectedclients,availableclients)" />
<input id="moveleftall" type="button" value="<<" ng-click="moveAll(selectedclients,availableclients)" />
</div>
<div style="float:left">
<div>Selected Clients</div>
<div>
<select size="5" multiple ng-model="selected" ng-options="client as client.name for client in selectedclients" style="width: 100px;height:100px"></select>
</div>
</div>
<div style="clear:both">
<br/>
<div>Selected Clients: {{selectedclients}}</div>
<div>Available Clients: {{availableclients}}</div>
<div>Selected: {{selected}}</div>
<div>Available: {{available}}</div>
</div>
</body>
</html>
Credit goes to AngularJS moving items between two select list for the base. However, it would only move single items when multiple items are selected.

Converting Datetime in month using AngularJs

I'm consuming json data in an array. In each row I have a datetime field.
Each datetime field represents data in this form 2016-11-19 00:00:00.
I want to show date and month separate as separate values.
It's my code:
<span class="day">8</span>
<span class="month">{{ event.event_date | date:'MMM' }}</span>
<span class="year">2014</span>
<span class="time">12:00 AM</span>
I have a simple solution to this:
In controller:
$scope.myDate = new Date("2016-11-19 00:00:00");
$scope.myDate_month = $scope.myDate.getMonth();
$scope.myDate_day = $scope.myDate.getDate();
$scope.myDate_year = $scope.myDate.getFullYear();
$scope.time = $scope.myDate.getHours();
$scope.time = $scope.myDate.getMinutes();
In html:
<span class="day">{{myDate_day}}</span>
<span class="month">{{myDate_month}}</span>
<span class="year">{{myDate_year}}</span>
<span class="time">{{myDate | date: 'h:mm a'}}</span>
Since your dates are strings, you should parse them to Date, like this:
$scope.event_date = new Date("2016-11-19 00:00:00");
Then you can call your filter in view:
<span ng-bind="date | date:'MMM'"></span>
Example:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.events = [];
// Simulation of $http.get
for (var i = 1; i < 10; i++) {
$scope.events.push({
"id": Math.floor(Math.random() * 100) + 1,
"event_date": "201" + i + "-0" + i + "-" + i + " 0" + i + ":00:00"
})
}
// Parsing your strings to date objects
$scope.events.map(function(value) {
value.event_date = new Date(value.event_date);
})
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div ng-repeat="event in events track by $index">
<!--
<span class="day">8</span>
<span class="month" ng-bind="event.event_date | date:'MMM'"></span>
<span class="year">2014</span>
<span class="time">12:00 AM</span>
-->
<span class="day" ng-bind="event.event_date | date:'dd'"></span>
<span class="month" ng-bind="event.event_date | date:'MMM'"></span>
<span class="year" ng-bind="event.event_date | date:'yyyy'"></span>
<span class="time" ng-bind="event.event_date | date:'HH:mm'"></span>
</div>
</body>
</html>
Check the API of the date-filter.

Initialise a select in AngularJs

I have a select that should track a myCoef as a float value(not an object, but a float value).
I have the following code (CodePen HERE):
function theController($scope) {
$scope.coefs = [
{name:'mm', val:1/1000},
{name:'cm', val:1/100},
{name:'m', val:1}
];
$scope.myCoef = 1/100;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<body ng-app>
<div ng-controller="theController">
<select ng-model="myCoef"
ng-options="coef.name for coef in coefs track by coef.val">
</select>{{myCoef}}
</div>
</body>
How do I correctly initialise my select, in order to keep a float value in myCoef?
Use As syntax and remove track by.
PS : If someone knows why i have to remove track by he can edit my answer because i don't really know why.
function theController($scope) {
$scope.coefs = [
{name:'mm', val:1/1000},
{name:'cm', val:1/100},
{name:'m', val:1}
];
$scope.myCoef = 1/100;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<body ng-app>
<div ng-controller="theController">
<select ng-model="myCoef"
ng-options="coef.val as coef.name for coef in coefs">
</select>{{myCoef}}
</div>
</body>
A little strange syntax. Following the Walfrat answer, examples how to init by val, or by name the initial value (without passing via $scope.myCoef = $scope.coefs[1] syntax)
function theController($scope) {
$scope.coefs = [
{name:'mm', val:1/1000},
{name:'cm', val:1/100},
{name: 'm', val:1}
];
$scope.myCoefVal = 1/1000;
$scope.myCoefName = 'cm';
}
<body ng-app>
<div ng-controller="theController">
Init by value - myCoefVal=1/100 <br>
<select ng-model="myCoefVal"
ng-options="coef.val as coef.name for coef in coefs">
</select><br>
now myCoefVal={{myCoefVal}}
<br/><br/>
Init by name - myCoefName='cm'<br>
<select ng-model="myCoefName"
ng-options="coef.name as coef.name for coef in coefs">
</select><br>
now myCoefName='{{myCoefName}}'
</div>
</body>

Resources