How can I have a ng-model in btn-group - angularjs

How can I have a ng-model in a btn-group? It's working like radio buttons, and I need to control the answer every time I click in one specific button.
Here is my code:
<div class="btn-group">
<button type="button" class="btn btn-sm btn-primary"
ng-click="icc.model.investigacao.dadoClinicoDoencaPreExCollection.statusDiabetes = 1"
ng-class="icc.model.investigacao.dadoClinicoDoencaPreExCollection.statusDiabetes == 1 ? [''] : ['btn-info']">
Yes
</button>
<button type="button" class="btn btn-sm btn-primary"
ng-click="icc.model.investigacao.dadoClinicoDoencaPreExCollection.statusDiabetes = 2"
ng-class="icc.model.investigacao.dadoClinicoDoencaPreExCollection.statusDiabetes == 2 ? [''] : ['btn-info']">
No
</button>
<button type="button" class="btn btn-sm btn-primary"
ng-click="icc.model.investigacao.dadoClinicoDoencaPreExCollection.statusDiabetes = 9"
ng-class="icc.model.investigacao.dadoClinicoDoencaPreExCollection.statusDiabetes == 9 ? [''] : ['btn-info']">
Ignored
</button>
</div>
In the end I need to validate these custom "radio buttons". How can I do that?

You can use Bootstrap to style your radio buttons as toggle buttons. This will allow you to keep the input type for use of ng-model and form validation, without using your ng-click method above.
Here is a simple demo in a fiddle.
Controller:
var app=angular.module('myApp', []);
app.controller('MyCtrl', function MyCtrl($scope) {
$scope.people = [{
name: "John"
}, {
name: "Paul"
}, {
name: "George"
}, {
name: "Ringo"
}];
$scope.choices = {};
});
HTML:
<form name="myForm" ng-app="myApp" ng-controller="MyCtrl">
<p>Favorite Beatle</p>
<div class="btn-group-vertical" data-toggle="buttons">
<label class="btn btn-primary" ng-repeat="person in people">
<input type="radio" name="options" id="option1" autocomplete="off" ng-model="choices.SelectedPerson" value="{{person.name}}" required> {{person.name}}
</label>
</div>
<p><tt>myForm.$invalid: {{myForm.$invalid}}</tt></p>
You chose: <strong>{{choices.SelectedPerson}}</strong>
<button ng-disabled="myForm.$invalid">Submit</button>

You have very similar buttons code. I advise you to generate them from the model. And you will no problem to link them to controller.
Here is code example:
in controller:
$scope.buttonChecked = 1;
$scope.buttons = [
{
text: 'Yes',
value: 1
}, {
text: 'NO',
value: 2
}, {
text: 'Ignored',
value: 9
}
];
And the view:
<div class="btn-group">
<button ng-repeat="button in buttons" type="button" class="btn btn-sm btn-primary"
ng-click="buttonChecked = button.value"
ng-class="buttonChecked == button.value ? [''] : ['btn-info']">
{{button.text}}
</button>
</div>
I am not sure how do you want represent the changes, but if you will explain that more detail I will edit an answer, hope it will help you!
Updated

I had a situation like that one and I solve it like so:
I used the li to position the buttons and are the "real" clickable element the <button>... are just for looks :D
<ul>
<li ng-repeat="item in buttons" ng-show=item.view ng-click="goToNgRepeat(item.op);" ng-style="{'display':'inline-block'}">
<button class="menuBtn" ng-style="{'width':item.size, 'height':menuButtonHeight}"><b>{{ item.tx }}</b></button>
</li>
</ul>
and solve the which one was pressed with ng-click calling a function and passing a value, the value is defined in the button array:
$scope.buttons = [
{ "tx": "Alm Extn", "op": 0, "view": true, "viewCont": false, "file": "TXT/extn.htm", "size": topicButtonsPos.menuButtonW },
{ "tx": "DS", "op": 1, "view": true, "viewCont": false, "file": "TXT/Ds.htm", "size": topicButtonsPos.menuButtonW },
{ "tx": "CDnt", "op": 2, "view": true, "viewCont": false, "file": "TXT/C.htm", "size": topicButtonsPos.menuButtonW },
{ "tx": "CDnt", "op": 3, "view": true, "viewCont": false, "file": "TXT/CA.htm", "size": topicButtonsPos.menuButtonW },
...
];
This array content op which I use as button value.
Hope it helps.

Related

Need to Assign Value of Bootstrap Dropdown in Angular UI-Grid to Row.Entity

I need to use a Bootstrap dropdown-menu in my ui-grid cellTemplate, and capture the selection in order to show their selection on the button. The problem is that because I can't use ng-model on a <li>, when I capture the selection, all of the dropdowns in the grid are updated with the selection text.
Here is a Plunker demonstrating my issue.
Here is my Controller code:
$scope.actions = [
{ id: 'action1', name: 'Action 1' },
{ id: 'action2', name: 'Action 2' }
];
$scope.selectedAction = { id: 'action0', name: 'SelectOne' };
$scope.setAction = function (action) {
$scope.selectedAction = action;
$scope.submitAction();
};
$scope.submitAction = function () {
console.log($scope.selectedAction.id);
};
$scope.gridOptions = { rowHeight: 38 };
$scope.gridOptions.columnDefs = [
{ name: 'id', enableCellEdit: false },
{ name: 'name', displayName: 'Name (editable)' },
{ name: 'age', displayName: 'Age' , type: 'number' },
{
field: 'Action', displayName: 'Action',
cellClass: 'center',
cellTemplate: 'myDropDown.html',
enableSorting: false
}
];
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
.success(function(data) {
$scope.gridOptions.data = data;
});
Here is my HTML:
<div class="ui-grid-cell-contents">
<div class="btn-group" dropdown dropdown-append-to-body>
<button type="button" class="btn btn-xs btn-primary dropdown-toggle" dropdown-toggle ng-click="grid.appScoe.submitAction()">
{{grid.appScope.selectedAction.name}}<span class="caret"></span>
</button>
<ul class="dropdown-menu" style="width:230px"><li ng-repeat="action in grid.appScope.actions"><span ng-click="grid.appScope.setAction(action)">{{action.name}}</span></li></ul>
</div>
</div>
Any assistance is greatly appreciated!
I have forked your plunker here
You're binding the selection to a single scope variable when you need to bind it to a model per grid row. Your model needs a column called Action to correspond with your grid config. For the sake of the example I simply added a column:
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
.success(function(data) {
data.map(function(element) {
element.Action = $scope.selectedAction;
});
$scope.gridOptions.data = data;
});
I modified setAction() to pass in the row and the selected action:
$scope.setAction = function(row, action) {
row.entity.Action = action;
$scope.submitAction();
};
And changed your cell template to work with the controller changes:
<div class="ui-grid-cell-contents">
<div class="btn-group" dropdown dropdown-append-to-body>
<button type="button" class="btn btn-xs btn-primary dropdown-toggle" dropdown-toggle ng-click="grid.appScoe.submitAction()">
{{row.entity.Action.name}}<span class="caret"></span>
</button>
<ul class="dropdown-menu" style="width:230px"><li ng-repeat="action in grid.appScope.actions"><span ng-click="grid.appScope.setAction(row, action)">{{action.name}}</span></li></ul>
</div>
</div>

How to show glyphicon eye based on value in Angularjs?

I have glyphicon-eye for all fields in the form. If user click on glyphicon-eye-open then it will change to glyphicon-eye-close and I push that specific field name into an array.
In my JSON response I am getting the hidden field values but how can I use that value and call exact glyphicon-eye.
JSON response :
{
"response": {
"status": {
"code": "0",
"message": "Success"
},
"service": {
"servicetype": "4",
"functiontype": "1005"
},
"data": {
"session_id": "372",
"roles": [
{
"hiddenfields": [
{
"fname": "firstname",
"fblink": "fblink",
"country": "country",
"martialStatus": "martialStatus"
}
]
}
]
}
}
}
Controller :
$scope.user = {
fname: "firstname",
lname: "lastname",
dob: "dob",
gender: "gender",
country: "country",
state: "state",
city: "city",
pincode: "pincode",
martialStatus: "martialStatus",
emailId: "emailId",
mobile: "mobile",
qualification: "qualification",
fblink: "fblink"
};
$scope.allow = {};
$scope.users = [];
$scope.push = function(){
$scope.users = [];
var user = {},
allow = $scope.allow;
console.log(allow);
Object.keys(allow).forEach(function(key){
allow[key] ? user[key] = $scope.user[key] : null;
});
$scope.users.push(user);
}
HTML :
<a class="menu-toggle" class="btn btn-default" ng-model="allow.fname"><i class="glyphicon" ng-class="{'glyphicon-eye-open':allow.fname, 'glyphicon-eye-close':!allow.fname}" ng-click="push(allow.fname = allow.fname?false:true)"></i></a>
If field value is in array then I need to show glyphicon-eye-close.
You can use ng-class like below.
<div class="form-group" ng-repeat="x in allow" >
<button class="btn btn-default"><span class="glyphicon" ng-class="{ 'glyphicon-eye-open': x.fname==0 , 'glyphicon-eye-close': x.fname==1}"></span> {{x.name}}</button>
</div>
function myCtrl($scope) {
$scope.allow=[{
'fname':1,
'name':'Anil'
},{
'fname':0,
'name':'Sunil'
},{
'fname':1,
'name':'Manil'
}]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div ng-app ng-controller="myCtrl" class="col-md-12">
<div class="form-group" ng-repeat="x in allow" >
<button class="btn btn-default"><span class="glyphicon" ng-class="{ 'glyphicon-eye-open': x.fname==0 , 'glyphicon-eye-close': x.fname==1}"></span> {{x.name}}</button>
</div>
</div>
Some times the ! doesnot works inside ng-clss. You please replace that by
<a class="menu-toggle" class="btn btn-default" ng-model="allow.fname">
<i class="glyphicon"
ng-class="{'glyphicon-eye-open':allow.fname.length > 0, 'glyphicon-eye-close':allow.fname.length == 0}"
ng-click="push(allow.fname = allow.fname?false:true)">
</i>
</a>
I am now able to glyphicon based on values by assigning the response to my model as below,
$scope.allow = response.data.roles[0].hiddenfields[0];

Ng-model with button

Good morning, I make a loop to catch "name " in an array and each "name " has variables with information. I need the ng -model receive the value of the "name " when I click on the "button" to oh yes I can make a loop in this "name".
div class="list-group" ng-repeat="rep in list.report">
<button type="button" class="list-group-item " ng-model="ctrl.x">
{{rep.name}}
</button></div>
If I understand your question correctly, is this what you're looking for?
https://jsfiddle.net/3ajtoyfm/
Angular
function Controller() {
var vm = this;
vm.rep = null;
vm.reps = [{
name: 'Jimmy Page',
band: 'Led Zeppelin'
}, {
name: 'Ozzy Osbourne',
band: 'Black Sabbath'
}, {
name: 'Trent Reznor',
band: 'NIN'
}];
vm.getRep = getRep;
function getRep(rep) {
vm.rep = rep;
}
}
HTML
<button ng-repeat="rep in ctrl.reps" ng-click="ctrl.getRep(rep)">{{rep.name}}</button>
<br>
<div ng-if="ctrl.rep">
<h4>
Rep
</h4> {{ctrl.rep.name}} - {{ctrl.rep.band}}
</div>
ng-model won't work with the button use ng-click :
<div class="list-group" ng-repeat="rep in list.report">
<button type="button" class="list-group-item" ng-click="ctrl.x = rep.name">
{{rep.name}}
</button>
</div>

Push Item to Model within a nested Repeat doesn't appear in view

I've done a small working snippet so far to handle 'notes'. But now I do need to add Items at Runtime to my Model.
That's the JSON behind my Model:
[
{
"DocId":"SomeGuid",
"Items":[
{
"Content":"SomeContent",
"Date":"SomeDate",
"OrderBy":0,
"Page":1,
"Title":"SomeTitle"
},
{
"Content":"SomeContent",
"Date":"SomeDate",
"OrderBy":0,
"Page":2,
"Title":"SomeTitle"
}
]
},
{
"DocId":"SomeGuid",
"Items":[
{
"Content":"SomeContent",
"Date":"SomeDate",
"OrderBy":0,
"Page":1,
"Title":"SomeTitle"
},
{
"Content":"SomeContent",
"Date":"SomeDate",
"OrderBy":0,
"Page":2,
"Title":"SomeTitle"
}
]
}
]
I now need to add a new Entry in one of those .Items.
That's my code:
$scope.AddNode = function (docID, page) {
var item;
$scope.data.forEach(function(object) {
if (object.DocId == docID) {
var newNode = { Content: "", Page: page, Title: "Neue Haftnotiz", Date: "16.19.05",Id: 0,Order:0,DocId:docID };
$scope.data[$scope.data.indexOf(object)].Items.push(newNode);
return;
}
});
(btw is there any $scope.data.FindByAttribute('docId',docID)? - I couldn't find anything in this regard)
It'll push the new Item in my array, but won't update my view.
You see the results here: (Black = old, Red = pushed)
My View just doesn't care if there is a new element or not - here's the template:
template: '<div class="root" >\
<div class="group" id="{{groupId}}-{{$index}}" ng-repeat-start="doc in ngModel" sv-root sv-part="doc.Items">\
<div class="groupHeader" ><h4 style="margin-bottom:0px;" >{{doc.DocId}}</h4></div>\
<div class="note panel" ng-repeat="item in doc.Items" sv-element>\
<div class="header">\
<h5>\
<a ng-click="toggleCollapsedStates($parent.$index,$index)" class="anchor" href="#{{groupBaseId}}-{{$parent.$index}}-{{$index}}">{{item.Title}} - Seite: {{item.Page}}</a>\
</h5>\
<div class="button collapsed" id="{{groupBaseId}}-{{$parent.$index}}-{{$index}}-expander" ></div>\
<div id="{{groupBaseId}}-{{$parent.$index}}-{{$index}}-menu" class="collapse">\
<input type="button" class="button delete" ng-click="deleteNode($parent.$index,$index)"/>\
<input type="button" class="button edit" ng-click="editNode($parent.$index,$index)" id="{{groupBaseId}}-{{$parent.$index}}-{{$index}}-edit"/>\
<input type="button" class="button reference" ng-click="openReference($parent.$index,$index)"/>\
</div>\
</div>\
<div id="{{groupBaseId}}-{{$parent.$index}}-{{$index}}" data-parent="#{{groupId}}-{{$parent.$index}}" class="collapse">\
<textarea class="area" maxlength="255" id="{{groupBaseId}}-{{$parent.$index}}-{{$index}}-textarea" readonly>{{item.Content}}</textarea>\
</div>\
</div>\
</div>\
<div ng-repeat-end></div>\
</div>',
$scope.$apply() does the job
And the answer is too short.

binding data in ng-repeat angularjs

*This is my html file where i want to repeat chapters which is a array that looks like
My code gives binds the selected checked boxes only (Index values) to true. But i need the entire list of chapters and their i.d's to be retrieved on submit.
Cannot figure out how to iterate it on nested loops *
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-repeat="chapter in chapters">
<label><input type="checkbox" name="checkbox" value="{{chapter}} ng-model="escConfigForm.chapters[$index]" >{{chapter.name}}</label><br>
</span>
<input type="submit" id="save" value="Save" />
$scope.chapters = chapterService.getChapters($scope.isbn);
$scope.submit = function(escConfigForm) {
var postData = {
content_items: JSON.stringify({
"#context" : [],
"#graph" : [ {
"#type" : "ContentItemPlacement",
"placementOf" : {
"#type" : "LtiLink",
"text" : escConfigForm.examName,
"mediaType" : "application/vnd.ims.lti.v1.launch+json",
"title" : "Exam Study Center",
"custom" : {
"dueDate" : escConfigForm.examDueDate,
"targetScore" : escConfigForm.examTargetScore,
"chapters" : escConfigForm.chapters
},
"activityType" : "other",
"activityRefId" : $scope.escId
}
} ]
}),
data: $scope.data
};
postForm($scope.postUrl, postData);
var configData = {
"activityRefId" : $scope.escId,
"dueDate" : escConfigForm.examDueDate,
"targetScore" : escConfigForm.examTargetScore,
"chapters" : escConfigForm.chapters
};
console.log($scope.chapters);
JSON file:
[{"name":"Chapter 1: Negative Messages","id":"832115"},{"name":"Chapter 2: Physics","id":"832115"},...]
I would recommend maintaining a list of the selected objects in the controller.
using this post as referenece: How do I bind to list of checkbox values with AngularJS?
I created this fiddle: http://jsfiddle.net/ruwk5r0v/7/
<div ng-app="formExample">
<div ng-controller="ExampleController"> <span ng-repeat="chapter in chapters" ng-click="checkboxChange($index)" ng-checked="selection.indexOf($scope.chapters[$index]) > -1">
<input type="checkbox" name="checkbox" value="{{$index}}" />
{{chapter.name}}
<br>
</span>
<br>
<input type="submit" ng-click="submitForm()" id="save" value="Save" />
<div> <span ng-repeat="chapter in selection">
<span>
{{chapter.name}}
</span>
<br>
</div>
and the js:
angular.module('formExample', []).controller('ExampleController', ['$scope', function ($scope) {
$scope.chapters = [{
"name": "Chapter 1: Negative Messages",
"id": "832115"
}, {
"name": "Chapter 2: Physics",
"id": "832115"
}];
$scope.submitForm = function () {
console.log(selection);
}
$scope.selection = []
$scope.checkboxChange = function(index){
var chapter = $scope.chapters[index];
var idx = $scope.selection.indexOf(chapter);
if (idx > -1){
$scope.selection.splice(idx, 1);
} else {
$scope.selection.push(chapter);
}
}
}]);
here you can very easily implement your submit function, just use the new selection object.
This really should be moved into a directive, but don't have time to write that right now :P
Here I created a controller for the snippet, and added some data to $scope.chapters object, and it is displaying correctly. The values disappear when selected, but that is another issue.
angular.module('myApp', [])
.controller('myCtrl', ['$scope',
function($scope) {
$scope.chapters = [{
name: 'Chapter 1: Negative Messages',
id: "1",
isSelected: false
}, {
name: 'Chapter 2: Physics',
id: "2",
isSelected: false
}];
$scope.submitItems = function(chapters) {
alert(JSON.stringify(chapters));
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<span ng-repeat="chapter in chapters">
<input type="checkbox" name="checkbox" value="{{chapter}}"
ng-model="chapter.isSelected" />
{{chapter.name}}
</span>
<br>
<form ng-submit="submitItems(chapters)">
<input ng-model="chapters" type="submit" id="save" value="Save" />
</form>
</div>
</div>
Edit: Updated the code to reflect the OP needs.

Resources