Passing checkbox values to controller in Angular JS - angularjs

I have a group of checkboxes which are populated from,the database. Each checkbox value contains a Book Id.
Now I have a Save button which contains a ng-click="save()" function. How can I pass the value of checked book Ids to the controller, and how can I catch the array of Ids in the controller' save() method. How can I bind the checkbox values, with the controller, here?
Here is the code in the view,
<div ng-repeat="bk in Books">
<input type="checkbox" value={{bk.Id}} ng-checked="$index ===0 ? true : false"/>{{bk.Name}}
</div>
<br/>
<input type="button" id="save" class="btn btn-success" value="Save" ng-click="save()"/>
<br/>

You don't need to pass the Ids values from the view, you can grab them directly within the controller through the binding mechanism.
Here you have a working sample. Whit this you can get rid of value={{bk.Id}} and ng-checked="$index ===0 ? true : false". Also notice how it is initialized the state (checked or unchecked) of the checkbox: ng-init="bookModel[bk.Id] = $first" which sets the checkbox checked only for the first element in the list.
angular
.module('app', [])
.controller('ctrl', function($scope) {
$scope.Books = [{
Id: 1,
Name: "Harry Potrer"
},
{
Id: 2,
Name: "Python"
},
{
Id: 3,
Name: "C#"
}
];
$scope.bookModel = {};
$scope.save = function() {
var checkedBooks = [];
for (var k in $scope.bookModel) {
if ($scope.bookModel.hasOwnProperty(k) && $scope.bookModel[k]) {
checkedBooks.push(k);
}
}
//do your stuff with the ids in `checkedBooks`
alert(checkedBooks);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-app="app" ng-controller="ctrl">
<div ng-repeat="bk in Books">
<input type="checkbox" ng-model="bookModel[bk.Id]" ng-init="bookModel[bk.Id] = $first"/>{{bk.Name}}
</div><br/>
<input type="button" id="save" class="btn btn-success" value="Save" ng-click="save()" />
</span>

Related

Angularjs cannot perform crud operations from accordion

I am trying to add a form to a bootstrap accordion and post a text value. Without accordion the form works alright. When i added the form to the accordion i am not able to pass text box value to angularjs controller. Basically i am not able to perform the CRUD operations as i am not able to pass the values. Minimum code related to the issue.
main.html
<div ng-controller="myController">
<accordion class="accordion" close-others="oneAtATime">
<accordion-group ng-repeat="group in groups" is-open="status.isOpen[$index]" >
<accordion-heading>
{{group.groupTitle}} <i class="fa chevron-icon" ng-class="{'fa-chevron-down': status.isOpen[$index], 'fa-chevron-right': !status.isOpen[$index]}"></i>
</accordion-heading>
<div ng-include="group.templateUrl"></div>
</accordion-group>
</accordion>
</div>
controller.js
App.controller('myController', ['$scope', 'Parts', function($scope, Parts) {
var original = $scope.parts;
$scope.submit = function() {
if ($scope.parts.a_id == null) {
$scope.createNewPart();
} else {
$scope.updatePart();
}
};
$scope.createNewPart = function() {
Parts.resource1.create($scope.parts);
};
$scope.updatePart = function() {
Parts.resource2.update($scope.parts)
};
$scope.oneAtATime = true;
$scope.groups = [{
groupTitle: "ADD 1",
templateUrl: "file1.html"
}, {
groupTitle: "ADD 2",
templateUrl: "file2.html"
}];
$scope.status = {
isOpen: new Array($scope.groups.length)
};
for (var i = 0; i < $scope.status.isOpen.length; i++) {
$scope.status.isOpen[i] = (i === 0);
}
} ]);
file1.html
<div>
<form name="myForm" ng-submit="submit()">
<div class="row">
<label class="col-md-2 control-lable" for="part">Add1</label>
<input type="text" ng-model="parts.part" id="part" required />
</div>
<div class="row">
<input type="submit" value="{{!parts.id ? 'Add' : 'Update'}}" ng-disabled="myForm.$invalid">
</div>
</form>
//inside table
<tr ng-repeat="a in availableparts >
<td>{{a.id}}</td>
<td>{{a.apart}}</td>
<td><button type="button" ng-click="editPart(a.id)" >Edit</button>
<button type="button" ng-click="deletePart(a.id)">Remove</button>
</td>
</tr>
</div>
Initially, you need to set $scope.parts to empty object {}, so when you access $scope.parts.id you will have null, instead of error saying id of undefined

ng-dialog: input radio button value is undefined

I'm trying to get the radio value button value from ng-dialog but it always got undefined.
Here is the dialog template:
<script type="text/ng-template" id="flag-reasons.html">
<div style="padding:10px;">
<span>
What's wrong ?
</span>
<div class="form-group" ng-repeat="flagreason in flagreasons">
<input type="radio" ng-model="fr" name="frname" value="{{flagreason.id}}"> {{flagreason.title}}
</div>
<div class="form-group">
<button type="button" ng-click="validFlag()">
Valider
</button>
</div>
</div>
</script>
Here is the partial js where I start with the dialog:
$scope.openFlag = function(){
$scope.dialog = ngDialog.open({ template: 'flag-reasons.html',
className: 'ngdialog-theme-default', scope: $scope });
$scope.validFlag = function(){
console.log($scope.fr);
}
}
I have tried ng-value as below:
<input type="radio" ng-model="fr" name="frname" ng-value="flagreason.id"> {{flagreason.title}}
but it still got undefined
Notice that it works when I directly set the value of the radio button like:
<input type="radio" ng-model="fr" name="frname" value="5"> {{flagreason.title}}
The issue is with ngmodel that's not getting update. You have to initialise ngmodel first in the template.
flag-reasons.html
<script type="text/ng-template" id="flag-reasons.html">
<div style="padding:10px;">
<span>
What's wrong ?
</span>
<div class="form-group" ng-repeat="flagreason in flagreasons">
<input type="radio" ng-model="cb.fr" name="frname" value="{{flagreason.id}}">{{flagreason.id}} - {{flagreason.title}}
</div>
<div class="form-group">
<button type="button" ng-click="validFlag()">
Valider
</button>
</div>
</div>
</script>
Controller
angular.module("app", ['ngDialog'])
.controller('Ctrl',function ($scope, ngDialog) {
'use strict';
$scope.cb = {};
$scope.flagreasons = [
{id: 1, title: 'title1'},
{id: 2, title: 'title2'},
{id: 3, title: 'title3'}
];
$scope.openFlag = function(){
$scope.dialog = ngDialog.open({ template: 'flag-reasons.html',
className: 'ngdialog-theme-default', scope: $scope });
$scope.validFlag = function(){
console.log($scope.fr);
}
}
$scope.$watch('cb.fr', function (v) {
console.log(v);
});
});
Working Fiddle: JSFiddle

Enable button when i have selected two values

I have two select i want to enable my button when i have selected values in my two select, i don't know how i can do this ?
JSFIDDLE
My HTML:
<div ng-app="myapp">
<fieldset ng-controller="FirstCtrl">
<select
ng-options="people.first for people in people_1"
ng-model="selectedPerson1"></select>
<select
ng-options="people.first for people in people_2"
ng-model="selectedPerson2"></select>
</fieldset>
<br/><button class="btn btn-primary" ng-click="platform=true">Comparer</button>
</div>
You can do this using the ng-disabled directive. I have amended your jsfiddle here: http://jsfiddle.net/p0t4cw84/3/. I moved the button into the scope of the controller FirstCtrl and added a method on the scope that will return true or false if values are selected.
$scope.enableCompare = function () {
return !($scope.selectedPerson1 && $scope.selectedPerson2);
};
I hope this helps.
Here you go.There are lot of issue in you fiddle.I fixed it.
http://jsfiddle.net/purpz7u3/
<div ng-app="myapp">
<div ng-controller="FirstCtrl">
<fieldset >
<select
ng-options="people.first for people in people_1"
ng-model="selectedPerson1" ng-change="check()"></select>
<select
ng-options="people.first for people in people_2"
ng-model="selectedPerson2" ng-change="check()"></select>
</fieldset>
<br/><button class="btn btn-primary" ng-disabled="checked">Comparer</button>
</div>
</div>
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.checked = true;
$scope.people_1 = [
{ id: 1, first: 'John' },
{ id: 2, first: 'Rocky' }
];
$scope.people_2 = [
{ id: 1, first: 'Rambo' },
{ id: 2, first: 'Balboa'}
];
$scope.check = function(){
if($scope.selectedPerson1 && $scope.selectedPerson2){
$scope.checked=false;
}
}
});

Removing items from LocalStorage with AngularJS

I'm trying to adapt one of the many to-do list examples built with AngularJS and LocalStorage to a little app of mine.
So far I'm able to create and save items into the LocalStorage, and to delete items both from the view and the LocalStorage. The problem I'm finding now is that when I delete items, the delete function won't delete the item I chose, but the first from the list.
For instance, if I have an array of 1-2-3-4 and I choose to delete the 3, it will always delete the 1, and then the 2, and so on.
Here's my code, being a beginner as I am, I'm sure I missed something...
angular.module('Logger', [])
.controller('TodoCtrl',['$scope', function($scope){
$scope.todos = extractJSONFromLocalStorage();
$scope.addTodo = function () {
$scope.todos.push({ text: $scope.formTodoText});
jsonToLocalStorage($scope.todos);
$scope.formTodoText = '';
};
$scope.kill = function (index) {
$scope.todos.splice(index, 1);
localStorage.removeItem(index);
jsonToLocalStorage($scope.todos);
};
function extractJSONFromLocalStorage() {
return JSON.parse(localStorage.getItem("todo")) || [
{text: 'learn angular', done: false},
{text: 'eat food', done: false},
{text: 'Click to remove', done: true}
];
}
function jsonToLocalStorage(todos) {
var jsonTodo = angular.toJson(todos);
if (jsonTodo != 'null') {
localStorage.setItem("todo", jsonTodo);
} else {
alert("Invalid JSON!");
}
}
}]);
And the HTML:
<h1><span class="modal-title">Edit drivers</span></h1>
<li ng-repeat="todo in todos">
<span class="done-true">{{todo.text}}</span>
<label class="delete pull-right" for='{{todo.text}}' ng-click="kill(index)">
<div><i class="fa fa-close"></i></div>
</label>
</li>
<h2>Add new driver<h2>
<form action="" class="form-horizontal controller" ng-submit="addTodo()">
<input class="form-control" type="text" placeholder="Enter driver name" ng-model="formTodoText" ng-model-instant>
<button class="btn btn-success form-control">Add</button>
</form>
Any tips would be highly appreciated!
try putting $index instead of index:
<label class="delete pull-right" for='{{todo.text}}' ng-click="kill($index)">

Angular JS binding scope data within ng-repeat to form

I have a collection of items in $scope.data with fields "id","name" & "age", that are being displayed in the view using ng-repeat directive.
For each set of items, there is a corresponding "edit button".
I want to be able to access values for the particular set of items for which edit button was pressed.
Html:
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<form ng-submit="submit()">
<input type="text" ng-model="i.id"/>
<input type="submit" value="Edit" />
</form>
</div>
</div>
Script:
function Ctrl($scope)
{
$scope.data = [
{id:1,name:"Alex",age:22},
{id:2,name:"Sam", age:28}
];
$scope.submit = function() {
//access id of user for which edit was clicked
};
}
What is the right way to do this?
Instead of a form, I would suggest you just use a button:
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<input type="text" ng-model="i.id"/>
<button ng-click="submit(i)">Edit</button>
</div>
</div>
Just send i into the button click event (I suppose you could use form if you need validation, but your example doesn't seem to need it).
Your submit function then changes to:
$scope.submit = function(selectedItem) {
// here you now have access to selected item
};
Try this:
HTML:
<form ng-submit="submit(i.id)">
JavaScript:
$scope.submit = function(userId) {
// you have userId
};
One option is to just use an ng-click within a button that calls your submit passing in i
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<button ng-click="submit(i);">edit</button>
</div>
</div>
and the function:
$scope.submit = function(i) {
console.log(i);
//access id of user for which edit was clicked
};
Here's a fiddle of that working: http://jsfiddle.net/pRAcP/

Resources