updating ng-model from ng-value directive - angularjs

I have a situation where I have couple of readonly fields in the form like with others to show the problem
You can see the las two inputs are readonly and they are calculated inputs where total debit is calculated by totalDebit function on $scope and total credit is calculated by totalCredit() function on the $scope. The problem is inputs only reflect ng-model values which is zero for both inputs and does not take value from calculating functions. A simplified controller is
app.controller('myController', ['$scope' ,function($scope){
$scope.credit = 0;
$scope.debit = 0;
$scope.debitSum = 0;
$scope.creditSum = 0;
$scope.totalCredit = function(){
return $scope.credit + 200; //just to show that it is calculated field
}
$scope.totalDebit = function(){
return $scope.debit + 200; //just to show that it is calculated field
}
}]);
If you remove ng-model directive from readonly inputs they will assume their values from totalDebit and totalCredit functions respectively. But I want them to use values from functions and also update $scope properties of totalDebit and totalCredit. Here is the plunker for this code

Should not be answer here (Why the ng-value is not doing what expected):
ngValue
Binds the given expression to the value of <option> or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.
And that is not our case...
Because, the ngValue is triggered on CHANGE. When we select radio or some option in the <select>
So, ng-value is not the proper setting in this scenario.
We can adjust it like this:
<input name="totalDebit" value="{{totalDebit()}}" readonly="" />
<input name="totalCredit" value="{{totalCredit()}}" readonly="" />
See updated plunker

Related

Is it possible to change the model being used on ng-model through ng-change?

I have a select element where the model is an attribute of a class. the class has attributes A and B.
<select ng-model="A" ng-options="x.CustomerId as x.Name for x in options.tableData.childCustomers"></select>
in the options, there's 1 option that is a specific id (let's say -1) while the others are 0 and above. if -1 is selected, I want the attribute B to be used as the model instead of A. is this possible to change in the controller?
Somewhat.
You can assign a value to B, but A will still exist normally.
You can put an ng-change by calling a function and checking the value of A, if A == -1 then B = something else B = ''.
Example:
add to html element(select):
ng-change="verifyValue()"
In AngularJS
$scope.verifyValue = function() {
$scope.B = '';
$scope.B = $scope.A == '-1'?'Negative Value':'';
}

Svelte - Binding a checkbox to toggle an input value

Using svelte, I want to set the default value of an input based on whether a checkbox is checked or not. The input is used in a drug dosage calculation. The calculation takes an value of weight in kg (k) x the input value.
I also need to have the drug calculation results change when this input value is changed by the checkbox action or when a user changes the input value manually, which doesn't happen currently.
I have been able to implement the input value change when the checkbox is checked but not clear on how to get the calculation to recalculate when the checkbox is checked or the input value is changed manually.
I need some help in integrating the correct input value into my calculation.
Checkbox:
let yes = false;
<input type=checkbox bind:checked={yes} >
Input:
<input value={yes? item.Fdosevalue : item.dosevalue} step={item.dosestep}
min={yes ? item.Fdosemin : item.dosemin} max={yes ? item.Fdosemax : item.dosemax} >
Calculation:
Not sure how to integrate the checkbox change in this calculation.
<span bind:this={k}> {( (k * item.dosevalue)).toFixed(1)} {item.appendvol} </span>
Here is a REPL which will hopefully make it a bit clearer
You can use data binding to accomplish this:
<input bind:value={...} />
You'll just need a place to store the values:
let values = {}
And then you bind to values with a unique key.
<input bind:value={values[item.name]}/>
Make sure to initialize the values dictionary with a default values for each fluid anytime the checkbox changes:
<input type=checkbox bind:value={yes} on:change={handleChange}/>
// initialize default values
function handleChange() {
const entries = fluids.map(item => {
const defaultValue = yes ? item.dosevalue : item.Fdosevalue
return [item.name, defaultValue]
})
values = Object.fromEntries(entries)
}

AngularJS ng-options to get selected option from an array that matches another scope var

I have an array and a var
$scope.fcFeedTypes = [{"name":"Plain Text","value":"Plain Text"},{"name":"MQ Message","value":"MQ Message"}];
}
$scope.feedEditor.ft = "MQ Message"; // this is dynamically obtained from some other source
I want a dropdown select with default selection based on the value of $scope.feedEditor.ft
HTML:
<select ng-model="fcFeedTypes"
ng-options="ft.name for ft in fcFeedTypes"
ng-init="ft=feedEditor.ft">
I am new to AngularJS and need some help...
If you just want the string "MQ Message" (or the value of whatever a user selects) as your ng-model value, then it's quite simple:
<select ng-model="someModelName"
ng-options="ft.value as ft.name for ft in fcFeedTypes"
ng-init="someModelName=feedEditor.ft">
If you want the full object as the ng-model value, then you've got to find the right one in JS. It must be referentially/strictly equal to the one in the options.
<select ng-model="someModelName"
ng-options="ft.name for ft in fcFeedTypes">
-
$scope.fcFeedTypes = [{"name":"Plain Text","value":"Plain Text"},{"name":"MQ Message","value":"MQ Message"}];
$scope.feedEditor.ft = "MQ Message"; // this is dynamically obtained from some other source
angular.forEach($scope.fcFeedTypes, function(feedType){
if(feedType.value === $scope.feedEditor.ft){
$scope.someModelName = feedType;
}
});

Angular using ng-bind-html and ng-model together in select dropdown?

Is it possible to use ng-bind-html and ng-model together on the same select dropdown? In my application I have a select dropdown that gets populated with ng-bind-html (which is working fine) but when I try to bind the value of the dropdown to the $scope with ng-model, it isn't updating the scope with the value of the dropdown, it just stays the same as the original declaration in my controller. Here is what it looks like:
<select id="newNumOfPlayers" ng-bind-html="compiledSelect" ng-model="newNumOfPlayers"></select>
I declare my variable at the start of my controller
$scope.newNumOfPlayers = 0;
And here is where I populate my select string
$scope.compiledSelect = "";
var contentSelectString = "";
for (i = 1; i <= data[0].noOfPlayersNeeded; i++) {
contentSelectString += "<option value="+i+">"+i+"</option>";
}
$scope.compiledSelect = $sce.trustAsHtml(contentSelectString);
but this always logs as 0
console.log("new number "+$scope.newNumOfPlayers);
Anyone have any ideas? Thanks
Is there any reason why you are using ng-bind-html instead of ng-options?
Here is a reasonably clean way to do this with just a number input:
First we create a filter that creates an array with numbers equal leading up to your threshold (number of players needed)
app.filter('range', function() {
return function(input, min, max) {
min = parseInt(min); //Make string input int
max = parseInt(max);
for (var i=min; i<=max; i++)
input.push(i);
return input;
};
});
Next up we use ng-options combined with our filter to populate the select
<select ng-model="newNumOfPlayers" ng-options="n for n in [] | range:1:noOfPlayersNeeded"></select>
Now newNumberOfPlayers should be updated correctly and the range filter doesn't pollute your controller and can be used whereever you need it. Please note that noOfPlayersNeeded should be in your scope.

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

Resources