I am creating a calendar like grid which generates numbers from 1 to 31 using two ng-repeats. Each element of the grid is a radio button, whose value I want to get inside a controller.
For example, user clicks on '12', the value gets stored somewhere, and on click of submit propagates to the controller.
The problem is that I am unable to read the value of the element checked.
Code:
<div data-toggle="buttons">
<div class="row" ng-repeat="date in dates track by $index" ng-if="$index % 5 == 0">
<label ng-class="{'btn-online': isOnline(i+1), 'btn-paper': isPaper(i+1)}" class="singleDate btn btn-default col-no-gutter col-xs-2 letter-box"
ng-repeat="i in [$index, $index + 1, $index + 2, $index + 3, $index + 4]"
ng-if="dates[i] != null">
<input type="radio" name="dates" id="date-{{i+1}}" ng-model="$parent.dueDate" ng-value="{{date[i]}}" class="date radio radio-primary">{{dates[i]}}
</label>
</div> <!--row div ends here -->
{{dueDate}} <!--no output here as well-->
</div>
<button type="submit" ng-click="changeDueDate(dueDate)" class="btn btn-block btn-default">Change Payment Due Date</button>
Don't Bind to Primitives
<!-- instead bind to objects -->
<button type="submit" ng-click="changeDueDate(obj.dueDate)">
Change Payment Due Date
</button>
Each ng-repeat and ng-if adds a new scope and level of hierarchy. Instead of counting levels of hierarchy, make dueDate a property of an object, obj.dueDate. Then prototypical inheritance will do its magic properly. For more information, see The Nuances of Scope Prototypal Inheritance.
Related
This problem has been frustrating me for the last couple days now so, here I am. I'll try to be as clear as possible.
I have an object to retrieve from the database. This object is used to create dropdown menus. It has two properties on it: A section property, which contains one string. The other property is called value, which contains all the possible options that the user can select in the dropdown. I use two nested ng-repeats in my HTML to create the dropdowns.
I am trying to send out to the database a formData object that has 2 properties in it: the name of the dropdown menu, and the value that the user selected. Appending the value selected from the dropdown menu is easy thanks to two way data binding that I set on the select element. However, I CANNOT figure out how to grab the value from the label element inside my controller so that I can attach it to my formData object. As far as I know, ng-model does not work on a label element. Here is the HTML, which hopefully will make it a bit more clear:
<form class="form-horizontal" ng-controller="PreferenceCtrl">
<div ng-repeat="(name, section) in configs">
<label ng-bind="name"></label>
<select class="form-control" ng-model="formData.settings[$index].value">
<option value="" disabled="disabled">---Please Select Option---</option>
<option ng-repeat="item in section" value="{{item.value}}" ng-bind="item.value">
</option>
</select>
</div>
<div class="col-md-12" ng-include="gametemp"></div>
<div class="row">
<div class="hr-line-dashed"></div>
<div class="text-center col-md-12 padding-15">
<button class="btn btn-primary btn-lg" ng-click="saveSetting()" formnovalidate translate>
<i class='fa fa-circle-o-notch fa-spin' ng-if="showBusy"></i> Save
</button>
</div>
</div>
</form>
Because the <select> class can have an ng-model attached to it, I can easily capture that value in my controller. I cannot do the same with the label. If anyone can help me out I will forever be your best friend. Thank you!
In answer to your question title "Is there a way to create a two-way binding on a label element", no, that isn't possible.
But if I understand correctly what you're trying to do, it sounds like you want to save data to the database based on information contained in both the <label> and it's associated <select>. If that's true, then I'd recommend using an ng-change function in your <select> like this:
<select class="form-control" ng-model="formData.settings[$index].value" ng-click="dropdownItemClicked(name, formData.settings[$index].value)">
<option value="" disabled="disabled">---Please Select Option---</option>
<option ng-repeat="item in section" value="{{item.value}}" ng-bind="item.value">
</option>
</select>
In your controller, create a function to handle this ng-click event:
$scope.dropdownItemClicked = function(name, value) {
console.log(name, value);
// save name/value to database
}
The key is to pass in the exact data you want to save to the database into your dropdownItemClicked() function.
Could you just put the value inside the label?
<label ng-bind="name">{{formData.settings[$index].value}}</label>
There is no way to read from the label. It is the one way binding after all, right. I would do something like this.
var app = angular.module('MyApp', []);
app.controller("MyCtrl", function($scope){
$scope.formData = {
settings:[]
};
$scope.configs = {
'Label1': [{ value: 11 }, { value: 12 }],
'Label2': [{ value: 21 }, { value: 22 }]
};
$scope.change = function(name, idx) {
$scope.formData.settings[idx].name = name;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-cloak="" ng-app="MyApp">
<form class="form-horizontal" ng-controller="MyCtrl">
<div ng-repeat="(name, section) in configs">
<label ng-bind="name"></label>
<select class="form-control" ng-model="formData.settings[$index].value" ng-change="change(name, $index)">
<option value="" disabled="disabled">---Please Select Option---</option>
<option ng-repeat="item in section" value="{{item.value}}" ng-bind="item.value">
{{item.name}}
</option>
</select>
</div>
<div class="col-md-12" ng-include="gametemp"></div>
<div class="row">
<div class="hr-line-dashed"></div>
<div class="text-center col-md-12 padding-15">
<button class="btn btn-primary btn-lg" ng-click="saveSetting()" formnovalidate translate>
<i class='fa fa-circle-o-notch fa-spin' ng-if="showBusy"></i> Save
</button>
</div>
</div>
<div>
{{formData.settings}}
</div>
</form>
</div>
This works:
<h4>Radio & Uncheckable Radio</h4>
<pre>{{radioModel || 'null'}}</pre>
<div class="btn-group">
<label class="btn btn-primary" ng-model="radioModel" btn-radio="'Left'">Left</label>
<label class="btn btn-primary" ng-model="radioModel" btn-radio="'Middle'">Middle</label>
<label class="btn btn-primary" ng-model="radioModel" btn-radio="'Right'">Right</label>
</div>
This doesn't work
{{radioModel || 'null'}}
<div class="btn-group">
<label class="btn btn-primary" data-ng-repeat="store in global.user.store" ng-model="radioModel" btn-radio="{{store}}" uncheckable>{{store}}</label><br>
</div>
If you select one radio button, the other radiobuttons don't de-select. Instead of having one radio button checked at a time, all 3 can be checked! And the {{radioModel}} won't display any value. For the first example, {{radioModel}} would display 'Left,' 'Right,' or 'Middle' depending on the value of btn-radio.
It's like data-ng-repeat="store in global.user.store" breaks the button behavior!
Try setting the scope variable with a dot, like if it an object.
$scope.radio = {model: null}; //for example
And use always radio.model instead of radioModel.
This is because the way the scope inheritance works each ng-model of the ng-repeat will generate a new scope. With the 'dot' rule you want have this problem.
Here is more information https://github.com/angular/angular.js/wiki/Understanding-Scopes
Try removing the {{}} in the btn-radio attribute :
<label class="btn btn-primary" data-ng-repeat="store in global.user.store" ng-model="radioModel" btn-radio="store" uncheckable>{{store}}</label>
I am trying to ask one question at a time like "How much did you score in X", when a user selects any of the given buttons, next question will be displayed, this will continue to a certain limit say 10.
Currently I'm displaying all those questions through a loop ng-repeat.
<div ng-repeat="subcode in subjects">
<label class="control-label" for="radios">How much did you score in SUBJECT {{subcode}}?</label>
<div class="btn-group btn-group-m">
<button ng-repeat="grade in gradebuttons" ng-click="saveclick(subcode,grade)" type="button" class="btn btn-default">{{grade}}</button>
</div>
<br/>
</div>
<button ng-click="calculate()">Calculate</button>
my calculate function uses the subcode,grade from saveclick function to process them and display the result just beneath the button.
Also I'm not sure how do I allow user to select just one button, like if they select A1 and again selects A2 in the same subject, previous A1 should be replaced. At this time all grades are selected from all subjects.
You can use ng-show to show current step by using $index and create a variable like currentStep
<div ng-repeat="subcode in subjects" ng-show="currentStep == $index">
which shows only the current question in the list while hiding others
You should update currentStep everytime you save a click to jump up to next question...
$scope.saveclick = function (subcode,grade) {
$scope.answers.push({'subcode' : subcode, 'grade' : grade});
$scope.currentStep++;
}
here is my PLUNKER
try something like
<div ng-repeat="i in [1,2,3,4,5,6,7,8,9]" ng-click="increment(j)" ng-show="$index+1 == j">
<div >{{$index}} How much did you score in SUBJECT {{i}}</div>
</div>`
increment is the scope method which increments the index.
I think you need something like this:
<div ng-repeat="subcode in subjects">
<label class="control-label" for="radios">How much did you score in SUBJECT {{subcode}}?</label>
<div class="btn-group btn-group-m">
<button ng-repeat="grade in gradebuttons" ng-click="saveclick(subcode,grade)"
type="button" class="btn btn-default" ng-show="selectedGrades[subjects[$parent.$index-1]] || $parent.$index== 0" ng-class="{selected: selectedGrades[subcode] == grade}" >{{grade}}</button>
</div>
<br/>
</div>
<button ng-click="calculate()">Calculate</button>
Your JS code:
$scope.saveclick = function (subcode,grade){
$scope.selectedGrades[subcode] = grade; //replace previous selected grade.
};
$scope.selectedGrades = {};
Try:
ng-show="selectedGrades[subjects[$parent.$index-1]] || $parent.$index== 0" to show 1 question at a time and show next when the previous question has been answered.
ng-class="{selected: selectedGrades[subcode] == grade}" to highlight the current selected grade for the subject.
DEMO
If you need to hide the entire question instead of just buttons, move the ng-show to the question and change it to ng-show="selectedGrades[subjects[$index-1]] || $index== 0"
DEMO
If you need to hide the question as soon as it's answer, try: ng-show="(selectedGrades[subjects[$index-1]] || $index== 0) && !selectedGrades[subcode]"
DEMO
I am trying to do inline editing on a table of data (See the plunkr)
<table class="table table-bordered">
<tr ng-repeat="data in dataset" >
<td ng-repeat="(key, value) in data" >
<div class="key-block">
<strong >{{key}}</strong>
</div>
<div class="val-block" inline-edit="data[key]" on-save="updateTodo(value)" on-cancel="cancelEdit(value)">
<input type="text" on-enter="save()" on-esc="cancel()" ng-model="model" ng-show="editMode">
<button ng-click="cancel()" ng-show="editMode">cancel</button>
<button ng-click="save()" ng-show="editMode">save</button>
<span ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false">
<span ng-hide="editMode" ng-click="edit()">{{model}}</span>
<a ng-show="showEdit" ng-click="edit()">edit</a>
</span>
</div>
</td>
</tr>
I can see in many places that we have to use a . in ng-model inside ng-repeat to avoid the scope issue. As I dont know the key already I am doing like data[key] for the model.
The input field blurs after I enter a single character.
The behavior you described is normal. If you look closely you will see that both the input value and the directive are bound to the same object i.e data[key]. When you change the value of the text input the model get updated ultimately triggering a refresh of the directive and you are back to the "list" view.
One easy solution to fix this is to use an intermediate variable between the directive and the input value and update the model only when the save button is clicked. Something like that :
//Directive
scope.newValue = null;
scope.edit = function() {
scope.editMode = true;
scope.newValue = scope.model;
$timeout(function() {
elm.find('input')[0].focus();
}, 0, false);
};
//Template
<input type="text" on-enter="save()" on-esc="cancel()" ng-model="newValue" ng-show="editMode">
You can see a modified plunker here.
I have a button group and am willing to update some other field on change according to the active buttons.
See the jsfiddle here
This is the HTML, copied from the documentation:
<div class="btn-group arrActiviteit arrUpdate" data-toggle="buttons">
<label class="btn btn-primary active" data-wat='foo'>
<input type="checkbox"> Item 1
</label>
<label class="btn btn-primary" data-wat='bar'>
<input type="checkbox"> Item 2
</label>
<label class="btn btn-primary" data-wat='something'>
<input type="checkbox"> item 3
</label>
<label class="btn btn-primary" data-wat='orElse'>
<input type="checkbox"> item 4
</label>
</div>
The Button row acts like it should do.
Then I watch for a click event on the .arrUpdate div for change. I've got multiple button groups which all have the .arrUpdate class. That's the reason for the second class: .arrActiviteit
$('.arrUpdate').click(function(e){
val = ''; // for holding the temporary values
$('.arrActiviteit label').each(function(key, value){
if(value.className.indexOf('active') >=0){
val += value.dataset.wat
}
})
// just for debug reasons.
$('#hierHier').html(val);
})
But it appears that the 'active' class gets added after the click event is fired. So the value in #hierHier is always behind one click, so to say.
How can I resolve this?
Or is there a better way to retrieve all the active buttons in this checkbox-array?
SOLVED
update: better solution Twitter Bootstrap onclick event on buttons-radio
http://jsfiddle.net/hA423/7/
I solved it using a timeout to make your function run after bootstrap events...
There must be some other ways to do it...
$('.btn').on('click',function(e){
setTimeout(count);
})