I'm trying to select a radio button using a variable but, although I can print the selected value the button does not stay selected.
This button is defined in an angular template as follows:
<a ng-click="selectNode($event, node)">
<input type="radio" name="library" style="float:left;" id="id-{{n}}" />
</a>
Where id is a GUID so is definitely unique.
Then, because it is the angular click event that is called when a button is selected I call this code in selectNode:
context.selectedNodes = [node];
$scope.selectedNode = node.$model.name;
var id = '#id-' + node.$model.id;
//console.log(typeof id);
//console.log(id);
$(id).prop("checked", true);
alert($("[name=library]:checked").val())
Which should theoretically check the radio button. However, it checks for a moment (it is checked when I call the alert) and then seems to disappear. I am however able to hardcode in an id and it stays checked.
I recommend diving more into the tools angular gives you to handle this things simply. If you need to track the value on this input, tie it to a model. If you want to process something once the checkbox has changed, use ng-change and tie it to a function.
<input type="radio" name="library" style="float:left;" ng-model=libraryModel ng-change="doSomething()" />
Keep in mind that doSomething() needs to be in scope, so in your controller, you need to define the function as $scope.doSomething(). Your model will also be attached to the $scope object, so you'd reference it as $scope.libraryModel. You can initialize the model as true or false as needed for a default value in the controller, then any user changes will auto update this value.
You're mixing jQuery and Angularjs, and it is not really worth. You can do the following just by using AngularJS ngModel, if you use AngularJs in your project.
Controller
function Controller($scope) {
//Init data input to value 1
$scope.data = ['1'];
}
HTML
<input type="radio" name="name" value="1" ng-model="data">
<input type="radio" name="name" value="2" ng-model="data">
Here, our $scope.data is set to 1 in our Controller, so it will match with the first input.
Related
I am creating a small application for my college project, I have a scenario where when the user clicks on a radio button an event should be fired.
My Angular code block:
<div ng-repeat="q in questionList " ng-if="ExamOver == false">
<h2>{{count+1}} .{{q.questionText}}</h2>
<ul>
<li ng-repeat="d in q.Choices">
<input type="radio" name="isCorrect" ng-model="correctAnswer.isworking" ng-change="getDetails($index,d,correctAnswer.isCorrect);" value="Yes" />
{{d.choiceText}}
</li>
</ul>
</div>
In my controller, I have this code:
$scope.correctAnswer = {isCorrect : false};
$scope.getDetails = function (index, choiceList, isCorrect) {
/* some logic... */
}
The events are firing only once per button, I am trying to work around this for past few hours without any progress, can someone please guide me what I am doing wrong here?
ng-change will be fired when the value of the variable you binded (with ng-model) changed. Here, all your radio buttons have the same value="Yes". That's is why ng-change is not triggered. From docs:
Evaluate the given expression when the user changes the input. The
expression is evaluated immediately, unlike the JavaScript onchange
event which only triggers at the end of a change (usually, when the
user leaves the form element or presses the return key).
The good solution depends of your needs, but where are some ideas:
Solution 1
Set different values for your inputs:
<li ng-repeat="d in q.Choices">
<input type="radio"
name="isCorrect"
ng-model="correctAnswer.isworking"
ng-change="getDetails($index, d, correctAnswer.isCorrect)"
ng-value="$index" />
{{d.choiceText}}
</li>
Solution 2
Fire your function whenever a radio is clicked:
ng-click="getDetails($index, d, correctAnswer.isCorrect)"
ngChange gets triggered if the value of ngModel changes.
Your radio buttons all have the same value namely "Yes"
<input type="radio" name="isCorrect" ng-model="..." ng-change="..." value="Yes" >
In my angular js app, I noticed that the DOM updates any time I call a function. This happens even when the function did not change any $scope variable.
I'm using an ng-repeat to create a set of checkboxes as shown below.
HTML
<a ng-click="someFunction()" >Some Function</a>
<form action="/settings/save">
<label>
<input ng-repeat="option in settings.active" name="options[]" value="{{option}}" checked="checked" />
{{option}}
</label>
<input type="submit" value="Save" />
</form>
JS
angular.module("myapp")
.controller("settingsCtrl", function($scope, $loadServ){
//$loadServ is a service for fetching data from the server
$loadServ("/settings/load")
.success(function(response){$scope.settings = response.data});
$scope.someVariable = "something";
$scope.someFunction = function(){
//There's nothing here yet
}
//More code follows
})
I noticed that all the unchecked checkboxes are checked when the "Some Function" button is clicked. I inspected the DOM and realised that all the checkboxes were re-rendered when the button was clicked.
Is there a way to update the DOM only when the $scope changes?
Note: I can't use one way binding because the $scope.settings.active can be changed by some other function
I've found the source of the error. It was caused by a filter that was applied far above the nodes
I have the following code:
<div data-ng-controller="MainController">
<input class="amount" type="text" name="" value="" />
<input class="result" type="text" name="" value=""/>
</div>
I want to take a numerical value from $scope and add it to a number entered by a user in the input with class "amount" and display the result in the input with class "result". So, basically, the variable is defined in the MainController function as the following:
$scope.cost = 100;
I'm a bit confused as to what the best way is to do this, I see there are ng-value and ng-model directives at my disposal but I am having a hard time understanding which is the right one for this application (and how to properly use them).
Seems like your application is asking for an inputs and they are going to submit there values OR gonna store it somewhere in DB. So ng-model (two way binding) will suits you application, which will update the value on model & view both.
Markup
<div data-ng-controller="MainController">
<input class="amount" type="text" ng-model="cost"/>
</div>
Above field will pre-populated as 100 and as you update it will also change $scope.cost value and the value if it is displayed on view anywhere.
Don't think about the ng-value that is only one way sort of binding. You can assign the value to input using ng-value="cost" that will only update the value attribute of input but when you update input from html you will never get those changes reflected inside cost scope variable as ng-value is meant for single way binding. Thinks like you should use use ng-value only when you want to display a value.
you should use ng-model
ng-value : Its a directive useful for evaluating expression and the value is bound to $scope used for evaluating expressions
ng-model : helps in two-way data binding ,view-->controller and vice versa moreover its a directive binds the value of HTML controls
I'm using Angularjs for a website and I now want to use a checkbox. I first created a checkbox like this:
<input type="checkbox" checked>
I can of course remove and add checked to my liking to have it checked by default or not. I now add a model to it (the model is not defined in the controller yet):
<input type="checkbox" ng-model="settings.mySwitch" checked>
The checkbox still displays, but all of a sudden the checked has no effect at all anymore; the checkbox is always unchecked by default.
Why oh why does the model prevent the checked from having any effect? All tips are welcome!
That is because when as the element is rendered browser sets checked property but then angular processes ng-model on the check box (whose value is falsy) and it gets unchecked. Instead if you do ng-checked="true" it will work (because ng-checked directive sets the property after ng-model is processed as its priority is lower than ng-model). But your model's initial state will get messed up (if using 1.3.x+), as ng-checked will not update the state of ng-model. So just set the ng-model value to true instead.
Just for demonstration i am using ng-init (You should set the ng-model initial value in the controller instead).
<input type="checkbox" ng-init="settings.mySwitch=true" ng-model="settings.mySwitch" />
See Demo with comparison:-
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app>
<p> With ng-checked {{settings.mySwitch}}
<input type="checkbox" ng-checked="true" ng-model="settings.mySwitch" />
<p> WIth Proper Initialization {{settings.mySwitch1}}
<input type="checkbox" ng-init="settings.mySwitch1=true" ng-model="settings.mySwitch1" />
</div>
Instead use ng-checked like this :
<input type="checkbox" ng-model="settings.mySwitch" ng-checked="true">
Edit: #PSL is right you should be using ng-init instead as it will mess up your ng-model.
<input type="checkbox" ng-init="settings.mySwitch=true" ng-model="settings.mySwitch" />
It is because of the initial value of settings.mySwitch. If you want the checkbox to be checked by default then instead of adding checked property you should set the initial value to true because when angular processes the template it will get its value and render the checked property accordingly.
How do I access hidden fields in angular? I have an app, where I want to submit a form for each of items in the list. The form is simple - it has submit button and a hidden field holding the ID value. But it does not work. The value is empty.
I updated the default angular example to display the situation - the todo text is in hidden field.
http://jsfiddle.net/tomasfejfar/yFrze/
If you don't want to hardcode anything in your javascript file, you can either load it via AJAX, or do:
<input type="hidden" name="value" ng-init="model.value=1" value="1">
this way, you can keep the form functionality with JS off, and still use the hidden field in AngularJS
If you want to pass the ID from the ng-repeat to your code, you don't have to use a hidden field. Here's what I did:
For example, let's say I'm looping through a collection of movies, and when you click the "read more" link it will pass your ID to your JS code:
<ul>
<li ng-repeat="movie in movies">
{{movie.id}} {{movie.title}} read more
</li>
</ul>
Then in your JS code, you can get the ID like this:
$scope.movieDetails = function (movie) {
var movieID = movie.id;
}
In your simpler fiddle, the problem can be fixed by using ng-init or setting an initial value in the controller. The value attribute won't effect the ng-model.
http://jsfiddle.net/andytjoslin/DkMyP/2/
Also, your initial example (http://jsfiddle.net/tomasfejfar/yFrze/) works for me in its current state on Chrome 15/Windows 7.
You can do something like this.
It is a dirty trick, but it works (like most dirty tricks ;-)
You just use the form name as Your hidden field
and always give the form the id "form"
<!doctype html><html ng-app><head>
<script src="angular-1.0.1.min.js"></script>
<script>
function FormController($scope) {
$scope.processForm = function() {alert("processForm() called.");
$scope.formData.bar = "";
try {$scope.formData.bar = document.getElementById("form").name;}
catch(e) {alert(e.message);}
alert("foo="+$scope.formData.foo+ " bar="+$scope.formData.bar);
};
}
</script></head><body>
<div ng-controller="FormController">
<form name="YourHiddenValueHere" id="form">
<input type="text" ng-model="formData.foo" />
<button ng-click="processForm()"> SUBMIT </button>
</form>
</div></body></html>
This allows You to use ONE Controller for ALL forms and send
them to ONE server script.
The script than distinguishes by the
form name (formData.foo) and knows what to do.
The hidden field names the operation in this scenario.
Voila - You have a complete application with as
many forms You want and one server script
and one FormController for all of them.
Simpler:
<input type="hidden" name="livraisonID" value="{{livraison.id}}"/>
It works!
Use ng-binding="{{employee.data}}". It will work properly.
I have to correct (improve) myself:
You can do it more elegantly:
<form>
<input type="text" ng-model="formData.foo" />
<input type="hidden" id="bar" value="YourHiddenValue" />
<button ng-click="processForm()"> SUBMIT </button>
</form>
and then in the JavaScript controller:
$scope.formData.bar = "";
try {$scope.formData.bar = document.getElementById("bar").value;}
catch(e) {alert(e.message);}
alert("foo="+$scope.formData.foo+ " bar="+$scope.formData.bar);
So you can have as many hidden fields as you like.