Getting value of AngularUI slider, and setting default/initial value of ng-bind - angularjs

I need to output the values and perform some calculations with the values of AngularUI sliders.
I have this mark-up:
<body ng-controller="sliderDemoCtrl">
<div ui-slider="{range: 'min'}" min="0" max="50" ng-model="demoVals.slider"></div>
<p>The value so far is:
<span ng-bind="demoVals.slider"></span> // I want this to show 0 until the slider is moved
</p>
<p>The calculated value is: <input type="text" ng-model="calculated" value=" {{ calculated }}" placeholder=0 /></p>
</body>
Firstly, I can't work out how to initialise that <span ng-bind="demoVals.slider"></span> with a default value of 0 or "None". At the moment it is blank until the slider moves. How can I set this to a default value?
Secondly, I want the value of {{ calculated }} to be a number multiplied by the value of the slider. How can I pass the value of the slider to ng-model="calculated" or access the value from within my controller?
Here's my Plunkr

You can set the initial value of the ng-model in the $scope:
$scope.demoVals = {};
$scope.demoVals.slider = 0;
And to keep the value of calculated in one way sync with the demoVals.slider, you can use a $watch on the $scope:
$scope.$watch('demoVals.slider', function (newVal) {
if (typeof newVal !== 'undefined') {
$scope.calculated = newVal * 3.14159; // Use any value here.
}
});
Working demo.

The way ng-model works, it binds to the scope property you define in it's attribute value in the markup. If no such scope property exists, it gets created on initialization.
Thus, to set start value just create that model property. To adjust another scope property based on changes to the slider model you can use $watch to listen for changes to the slider model property
app.controller('sliderDemoCtrl', function($scope) {
/* ng-model bound to this object, so define it's start value*/
$scope.demoVals={slider:10}
/* watch for changes*/
$scope.$watch('demoVals.slider',function(newVal,oldVal){
if(newVal){
$scope.calculated=2*newVal;
}
})
$scope.calculated = 0;
});
DEMO

Related

Checkbox with ng-model that reflect if another element is showed

I have an element checkbox, that I want to reset the value of ng-model when another element is not showed, example: set to false if another element is not showed in my view. ng-show only hide my checkbox, but not reflect in object of controller.
<select ng-model="item.myOption" convert-to-boolean>
<option value="false" selected>Option false</option>
<option value="true">Option true</option>
</select>
<input type="checkbox" ng-model="item.myChecked" ng-show="item.myOption">
You can write small function on ng-change of select field, in which you can set model value of checkbox to either true or false or null.
app.controller('myCtrl', function($scope) {
$scope.item = {myOption: "true"}
$scope.myCheckbox = true;
$scope.changed = function() {
if($scope.item.myOption == "false") {
$scope.myCheckbox = false;
} else {
$scope.myCheckbox = true;
}
}
});
http://plnkr.co/edit/ekNxZImNIBisBCrfZsFS?p=preview
Similarly, you can change any dependent field's value (like finding age field value right after user selects his DOB using datepicker, etc). You can use switchcase either for large set of values instead of if else inside change function

Angular slider change change value dynamically

I am working on a simple widget on angular slider. I use angular-slider library.
The core I idea is quite simple. I have a bar that has range between 0 to 1000. And two input fields.
The first field track the slider and displays the value of it e.g 100,50, 950 etc.
And the second field displays the value of slider, and multiplies that by 10.
For example the value on slider is 100 so the second field will display 1000.
Everything works fine except that the value on second field does not change dynamically.It changes only when I remove the previous value.
I use ng-change on my slider , however it does not work.
Maybe somebody has been working on angular slider and have done something similar.
Any help would be appreciated
(function() {
angular
.module('rzSliderDemo', ['rzModule', 'ui.bootstrap'])
.controller('MainCtrl', MainCtrl);
function MainCtrl() {
var vm = this;
vm.fisrtValue = 1000;
vm.multiply = multiply;
vm.sum = 0;
function multiply() {
vm.sum = vm.fisrtValue * 10;
};
multiply();
}
})();
<article>
<h2>Simple slider</h2>
<h2>Your Value is <i>{{vm.fisrtValue}}</i></h2>
<input ng-model="vm.fisrtValue" ng-change="vm.multiply()" />
<input ng-model="vm.sum" ng-change="vm.multiply()" />
<h2>Value multiply 10 times <i>{{vm.sum}}</i></h2>
<rzslider rz-slider-model="vm.fisrtValue" ng-change="vm.multiply()"></rzslider>
</article>

How to bind a list of checkboxes in AngularJS

I have a list of checkboxes as following :
<div flex="50" ng-repeat="formationType in formationTypeList">
<md-checkbox class="md-warn md-align-top-left"
value="{{formationType.codeFormation}}"
name="formationSelection[]"
ng-checked="formationSelection.indexOf(formationType) > -1"
ng-click="toggleFormationTypeSelection(formationType)">
{{ formationType.nom }}
</md-checkbox>
</div>
This is the format of formationSelection after I send my form :
formationSelection = [
{
codeFormation: 1,
nom: "ENSA"
},
{
codeFormation: 2,
nom: "CPGE"
}
]
In another scenario I want when I open my form to check the checkboxes which are defined in an array as following :
$scope.formationSelection = res.candidatureProjetProfessionnel.formations;
the object res.candidatureProjetProfessionnel.formations contains this :
formationSelection = [
{
codeFormation: 1,
nom: "ENSA"
},
{
codeFormation: 2,
nom: "CPGE"
}
]
And when I inspect $scope.formationSelection it contains the data I got from res.candidatureProjetProfessionnel.formations :
But I don't know why my checkboxes are not checked even though the $scope.formationSelection is not empty.
How can I solve this ?
i'm not sure what the md-checkbox directive is so i'm just going to use a normal checkbox input. Generally speaking, setting a default value for inputs in angular involves 2 things:
Make sure your inputs have ng-model to store the value of the checkbox and for 2 way data binding (so that you can set it from the controller as well)
In your controller set the variable declared in the ng-model to whatever default value you want.
So in you html:
<input type="checkbox" class="md-warn md-align-top-left" ng-
model="formationSelection[$index]" ng-true-value="{{formationType}}"
name="formationSelection[]">
Make sure you use ng-true-value to declare the value of each checkbox when checked. The ng-model is set to formationSelection[$index] which basically means each checkbox is an item inside the formationSelection array, this way the array will be the collection of the values of all checked inputs.
Now $scope.formationSelection = res.candidatureProjetProfessionnel.formations should work
Here's a working plunker:
http://plnkr.co/edit/sGm39DRWH9EOReiiSrIl?p=preview
You have to use ng-model as shown below.It should be an object like $scope.data = {};.This is just an example where hope you can get the point and work on your scenario. Actually you're having individual check boxes as shown below but values are being set through the loop.So you can apply this concept for your use case as well.Hope this will help to you.
Html
<md-checkbox ng-model="data.cb1" aria-label="Checkbox 1">
Checkbox 1: {{ data.cb1 }}
</md-checkbox>
JS
$scope.data = {};
$scope.data.cb1 = true;
Play with it on Codepen
I think that your method isFormation(formationType) on the directive ng-checked it's not return the result.
In your controller create a function
$scope.isFormation(_type){
return $scope.formationSelection.filter(function(f){return f.nom === _type;}).length > 0;
}

AngularJs ng-change event fire manually

<input type="checkbox" value="" ng-model="filterPrivateDocCheckBox" ng-click="dl.filterPrivateDocument(filterPrivateDocCheckBox, $event)">
<input st-search="target" class="input-sm form-control" ng-model="dl.documentTarget" ng-change="dl.change()" />
function filterPrivateDocument(val)
{
if(val)
this.documentTarget = 'Private';
}
When I clicked on checkBox I set the value into text box, but I saw ng-change event doesn't get fired. why?
And also When I type some value in text box I observe that ng-change event gets fired.
Any fix for this problem?
According to the docs:
The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.
It will not be evaluated:
if the value returned from the $parsers transformation pipeline has
not changed
if the input has continued to be invalid since the model
will stay null
if the model is changed programmatically and not by a
change to the input value
So it will not be triggered when it is changed by JavaScript (/angular).
What you can do, is trigger the change function yourself:
function filterPrivateDocument(val) {
if(val) {
this.documentTarget = 'Private';
this.change();
}
}
See this jsfiddle

unable to get ng-checked property for a radio button to check the button when populating a form

EDIT: for those of you who don't want to go through the code, I'm basically passing the form a "node" object with node.selectedAnswer = "4,1,4" or some string like that. The form has radio buttons and one of the buttons has a value "4,1,4". the radio button also has ng-checked="node.selectedAnswer" expression. But that doesn't work. I know for sure that node.selectedAnswer has the appropriate value.
I have a series of radio button questions that I'm asking the user. I want them to be able to go previous and next. I'm using a stack to store the data retrieved from ajax call, as well as selectedAnswer when they select an option and click next. I've commented the code itself to explain the situation where I can. Everything seems to be working, except ng-checked is just not picking up node.selectedAnswer, even though I can output {{node.selectedAnswer}} properly to the page.
<div class="container-fluid" ng-app="AccountRequest" ng-controller="GameNode" ng-init="outside={}">
<div class="row-fluid">
<div class="span2"></div>
<div class="span10">
<form>
<!-- node.selectedAnswer displays the selectedAnswer correctly when clicking previous and going back.
However, ng-checked is somehow not selecting the appropriate radio button. -->
<span>{{node.Question.Text}} selected answer: {{node.selectedAnswer}}</span>
<div class="radio" ng-repeat="answer in node.Answers">
<input type="radio" id="answerGroup" name="answerGroup" ng-checked="node.selectedAnswer" ng-model="outside.selectedAnswer"
value="{{answer.BranchId}},{{node.LeafId}},{{answer.Id}}"/> {{answer.Text}}
</div>
<div>
<input type="button" ng-click="previous()" value="Previous"/>
<input type="button" ng-click="next(outside.selectedAnswer)" value="Next"/>
</div>
</form>
</div>
</div>
</div>
//below is the script
app.controller('GameNode', function ($scope, $http) {
var nodes = [];
function load(branchId, leafId, answerId) {
$http.get("/AccountRequest/GetNode?branchId=" + branchId +
"&leafId=" + leafId +
"&answerId=" + answerId)
.success(function (data) {
//get data and push it in the stack
nodes.push(data);
$scope.node = data;
});
}
function populateValues(selectedAnswer) {
var answer = null;
if (selectedAnswer === undefined || selectedAnswer == null)
selectedAnswer = "0,0,0";
//when next is clicked, retrieve the selectedAnswer from form and store it in current node as a property.
if (nodes.length > 0) {
var curNode = nodes.pop();
curNode.selectedAnswer = selectedAnswer;
nodes.push(curNode);
}
answer = selectedAnswer.split(',');
if (answer != null) {
load(answer[0], answer[1], answer[2]);
}
}
$scope.next = populateValues;
$scope.previous = function () {
//when previous is clicked, pop the current node out and throw it away.
//then pop the previous node out, read it, and push it back in as current node.
if (nodes.length > 1) {
nodes.pop();
var prevNode = nodes.pop();
nodes.push(prevNode);
$scope.node = prevNode;
}
};
populateValues();
});
Older Answer - This works, (was marked correct) but using $parent can get a bit messy in nested repeats.
In this instance, you don't need to use ng-checked at all. Since this is a radio group, the checked attribute will be bound to the model. If the model is bound to the value of an individual radio button, then your ability to change which button is "checked" becomes very simple.
Here is a plunk that demonstrates the concept.
So in your case a few changes need to be made.
1. Get rid of 'id' attribute - the ID must be unique for each element.
2. Each item created in an ng-repeat creates its own child scope. So to access the original model, "$parent" must be invoked.
<input type="radio" name="answerGroup" ng-model="$parent.someAnswerAttribute"
value="{{answer.BranchId}},{{node.LeafId}},{{answer.Id}}"/>
In your controller define the model as you already did, then modify it to be tied to a value of a button, which in your case will be a bit lengthy, since you have multiple attributes within your value.
$scope.someAnswerAttribute = // exactly what the value of a radio button would be.
Again, the plunker above reflects this concept. Hope this helps!
..
..
Edit - Better Answer:
Since the ng-repeat creates its own child scope, and two-way binding is necessary, the ng-model should be referencing an object instead of a primitive. In other words, if the model was $scope.myModel="Biff", the child scope can not access that without invoking $parent (in the answer below). However, if the model is referencing a property of an object, the child will receive prototype inheritance of that object. (I think I said that right).
So using the older answer example, we can change:
From this in the parent controller:
$scope.someAnswerAttribute = "Biff";
To this in the parent controller:
$scope.someAnswerAttribute = {value: "Biff"}
And in the radio group:
<input type="radio" name="answerGroup" ng-model="someAnswerAttribue.value"
value="{{answer.BranchId}},{{node.LeafId}},{{answer.Id}}"/>
This plunk is forked from the older answer and demonstrates model as an object property.

Resources