angularjs checkbox ng-checked not working - angularjs

I have the following code :-
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
</head>
<body ng-app="app" ng-controller="ctrl" ng-init="init()">
<div class="container" style="width:400px">
<div class="panel panel-default">
<div class="panel-body">
<form>
<div class="form-group">
<label for="selectedBasket">Select basket :</label>
<select id="selectedBasket" class="form-control" ng-model="selectedBasket" ng-options="b.name for b in baskets">
</select>
</div>
<div ng-repeat="f in fruits" class="checkbox">
<label>
<input type="checkbox" value="" ng-checked="selectedBasket !== null && selectedBasket.items.indexOf(f) !== -1">
{{ f }}
</label>
</div>
</form>
</div>
</div>
</div>
<script>
var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
$scope.init = function() {
$scope.baskets = [{'name': 'mary', 'items': ['apple', 'orange']}, {'name': 'jane', 'items': ['banana']}];
$scope.fruits = ['apple', 'banana', 'cherry', 'orange', 'watermelon'];
$scope.selectedBasket = null;
};
});
</script>
</body>
</html>
if I select Mary or Jane, I can correctly see the correct items in their basket checked. However if I manually check all the fruits and then look at Mary or Jane, it doesn't exclude the items that are not in their baskets. Why is ng-checked failing?
Bonus question, is it best practise to set selectedBasket to null and checking for null in a directive assuming I want nothing as a default value, is there a better way?

You've got no ng-model in your checkbox so your manual action isn't registered anywhere.
ng-checked is only used to make a 'slave' checkbox it can take no manual action.
My guess is you should use a ng-model initialized to your ng-check value instead of using a ng-checked.
If you want to keep your ng-checked what you can do is :
<input type="checkbox" ng-click="selectedBasket.items.push(f)" ng-checked="selectedBasket !== null && selectedBasket.items.indexOf(f) !== -1">
in fact it's still wrong... must be tired, use a toogle function in your ng-click which add or remove the item should be better...

Had the same problem with ng-check, tried everything but nothing worked. I wanted to control the number of checked Items when clicked to 2, so I used the $Event sent with ng-click and disable it.
Here is a sample code:
<input type="checkbox" ng-click="toggleCheck($event, product._id);"
ng-checked="isChecked(product._id)">
$scope.toggleCheck($event, productId){
if ( $scope.featuredProducts.indexOf(productId) === -1) {
if ($scope.featuredProducts.length < 2) {
$scope.featuredProducts.push(productId);
}else {
$event.preventDefault();
$event.stopPropagation();
}
} else {
$scope.featuredProducts.splice( $scope.featuredProducts.indexOf(productId), 1);
}
}
$scope.isChecked(productId){
return ($scope.featuredProducts.indexOf(productId) !== -1);
}

Related

Writing an adding function in AngularJS

I'm new to AngularJS and I am doing some tutorials to get in touch with it. While I'm doing the tutorials I have modified the code a bit to get a better feeling of what's behind. My code consists of two parts, which have nothing to do with each other.
The first one is a simple user input and based on that a list gets filtered. This is working fine.
However, in the second part I was trying to implement a simple adding function where the user can give an input and based on that the sum of two numbers is calculated. This part is not working at all. The numbers are being recognised as strings. The code is basically from this source here. When I copy the whole code and run it, it works fine, but when I modify it a bit it doesn't.
I want to understand why my code isn't working. To me there is nearly no difference. So I think that I eventually misunderstood the concept of angularjs. But I can't figure out where the error could be.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
function TodoCtrl($scope) {
$scope.total = function () {
return $scope.x + $scope.y;
};
}
</script>
</head>
<body data-ng-app>
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</body>
</html>
Several things to change...
First you need to create a module:
var app = angular.module("myApp", []);
Then you need to define a module e.g. myApp on the ng-app directive.
<body data-ng-app="myApp">
Then you need to add TodoCtrl to the module:
app.controller("TodoCtrl", TodoCtrl);
Also check that both $scope.x and $scope.y have values, and make sure that they are both parsed as integers, otherwise you will get string concatenation ("1"+"1"="11") instead of addition (1+1=2)!
$scope.total = function () {
return ($scope.x && $scope.y)
? parseInt($scope.x) + parseInt($scope.y)
: 0;
};
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
(function(){
var app = angular.module("myApp", []);
app.controller("TodoCtrl", TodoCtrl);
function TodoCtrl($scope) {
$scope.total = function () {
return ($scope.x && $scope.y)
? parseInt($scope.x) + parseInt($scope.y)
: 0;
};
}
}());
</script>
</head>
<body data-ng-app="myApp">
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</body>
</html>
As mentioned in the above two answers adding TodoCtrl as controller instead function will make the snippet work.
REASON:
Angularjs framework above 1.3 does not support global function which means declaring controller as function wont work.
In your code snippet, you are using angular version 1.5, which needs the controller to be defined.
DEMO
angular.module("app",[])
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" >
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</div>
you need to define the TodoCtrl as controller instead function
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
Demo
angular.module("app",[])
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" >
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</div>

AngularJS: uncheck checkboxes with no ng-model attribute

I want to uncheck all checkboxes when press some button. I need to do this on AngularJS (no jQuery). My checkboxes don't have ng-model attribute. How I can uncheck them?
My HTML structure:
<li ng-repeat="channel in channelsList">
<div class="checkbox">
<label><input type="checkbox" value="" ng-click="isChecked(channel.id)">
<img src="images/checkbox-unchecked.png" alt="" class="unchecked">
<img src="images/checkbox.png" alt="" class="checked"><span>{{channel.name}}</span>
</label>
</div>
</li>
My channelsList is only an array of objects with 2 properties: id and name.
Thanks for helping!
Two ng-ifs
If you really want to avoid ng-model you could achieve the same effect with... notice the checked attribute
<li ng-repeat="channel in channelsList">
<div class="checkbox">
<label>
<input ng-if="isChecked(channel.id);" type="checkbox" checked ng-click="check(channel.id);">
<input ng-if="!isChecked(channel.id);" type="checkbox" ng-click="check(channel.id);">
<img src="images/checkbox-unchecked.png" alt="" class="unchecked">
<img src="images/checkbox.png" alt="" class="checked"><span>{{channel.name}}</span>
</label>
</div>
</li>
Bind checkbox ng-model to a _selected property.
Please note that I use _selected and not selected in case your API would in a near future return a selected property that would collide with this one.
index.html
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="SampleController">
<ul>
<li ng-repeat="channel in channelsList">
<input type="checkbox" ng-model="channel._selected" /> {{channel.name}} (id={{channel.id}})
</li>
</ul>
<button ng-click="uncheckAll()">Uncheck all</button>
</body>
</html>
script.js
angular.module('app', []);
angular.module('app').controller('SampleController', function ($scope) {
$scope.channelsList = [
{id: 'c1', name: 'CNN'},
{id: 'c2', name: 'BBC'},
{id: 'c3', name: 'Discovery Channel'}
];
$scope.uncheckAll = function() {
angular.forEach($scope.channelsList, function (channel) {
channel._selected = false;
});
};
});
Here is the plunker : http://plnkr.co/edit/VPOjKMUVyrMpPfT9jLz3
I don't know exactly what you need but supposing you have an array of ids telling the ids checked like this:
$scope.channelsList = [
{'id' : 1, 'name' : 'foo' },
{'id' : 2, 'name' : 'bar' },
{'id' : 3, 'name' : 'foo' }
];
var checked = [1, 3]
$scope.isChecked = function(id){
return checked.indexOf(id) >= 0;
};
You can put a button like:
<button ng-click="uncheckAll()">click</button>
And use it to clear your array:
$scope.uncheckAll = function(){
checked = [];
}

angularjs- dropdown value should be number not object

I have an array of objects that looks like
$scope.pArray = [{id: 0, name: 'bob'}, {id: 1, name: 'jen'}];
In my select dropdown, Im using ng-options instead of ng-repeat like so:
<select id="province" name="item" ng-model="obj.name" required
ng-options="item.id as prov.name for item in pArray track by item.id"></select>
Now when I hit the submit button, the value of obj.name is an object instead of the integer (0 or 1). How can I change this so that instead of the object, I get the id?
You can try this,
<select ng-model="selected" ng-options="emp.name for emp in pArray ">
</select>
DEMO
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.pArray = [{id: 0, name: 'bob'}, {id: 1, name: 'jen'}];
$scope.getselected = function(selected) {
alert(selected.id)
}
}
]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<div class="col-md-20">
<div id="main">
<form class="form-horizontal" role="form">
<label class="control-label col-md-2">Filter List:</label>
<div class="col-md-5">
<select ng-model="selected" ng-options="emp.name for emp in pArray ">
</select>
</div>
<button type="button" class="btn btn-primary" ng-click="getselected(selected)">selected</button>
</form>
</div>
</div>
</body>
</html>
Referring to the the angular docs:
https://docs.angularjs.org/api/ng/directive/ngOptions
You should try:
ng-options="item as item.name for item in pArray track by item.id"
You should try changing the "item.id as" to "item as" since you are using track by item.id. Also, did you mean "item.name" and not "prov.name"
Anyway, that's just quick and hopefully helpful place to start.

Uncheck checkbox with submit - AngularJS

I am trying to uncheck checkbox with submit button. The idea is when checkbox is checked button is shown, and when button is clicked checkbox is unchecked and button is hidden.
HTML page:
<html ng-app="myApp" ng-controller="myCtrl">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="script.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div ng-repeat="foo in boxes">
<div>
<input type="checkbox" name="cb" id="cb" ng-model="show" />{{foo}}
</div>
<div ng-show="show">
<form ng-submit="submit()">
<input type="submit" name="sumbit" id="sumbit" value="Hide" />
</form>
</div>
</div>
</body>
</html>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.boxes = ['a','b','c'];
$scope.submit = function(){
$scope.show = false;
}
});
On Plukner: http://plnkr.co/edit/z9W0w18dkgYJ3D5Q3aR2?p=preview
Thanks for any help!
The problem is that you're using a single variable to store states of 3 items yet Angular creates a scope for each context in the ng-repeat iteration. By changing show to an array and using $index to reference each of them, the show array from the main scope is passed to all three child scopes and there are no conflicts, so it works:
app.controller('myCtrl', function($scope) {
$scope.boxes = ['a','b','c'];
$scope.show = [];
$scope.submit = function(){
$scope.show = [];
}
});
HTML
<div ng-repeat="foo in boxes">
<div>
<input type="checkbox" name="cb" id="cb" ng-model="show[$index]" />{{foo}}
</div>
<div ng-show="show[$index]">
<form ng-submit="submit()">
<input type="submit" name="sumbit" id="sumbit" value="Hide" />
</form>
</div>
</div>
See it here: http://plnkr.co/edit/kfTMaLTXWtpt7N9JVHAQ?p=preview
(note sure if this is exactly what you wanted because there's no question, but it's enough to get you started)
UPDATE
And here is the version where Hide unchecks only "its own" checkbox ($scope.submit now accepts the index parameter): http://plnkr.co/edit/YVICOmQrPeCCUKP2tBBl?p=preview
You need to change the html code and simplify it as
Instead of form use simple ng-click
<div ng-show="show">
<input type="submit" value="Hide" ng-click="show = !show" />
</div>

Edit functionality in ng-controller

I am trying to display a list of objects from a controller and then trying to edit them.
I am binding data called editContact to value in input text box. I want to set a variable ii in scope and then when editing is done, then replace contacts[ii] with the temporary object editContact. But ii is not being recognized. Can I set a variable like ii?
<!doctype html>
<html ng-app>
<head>
<style>
</style>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
</head>
<body>
<div ng-controller="contactsController">
<label>Name</label>
<input ng-model="name" type="text" placeholder="Name">
<label>email</label>
<input ng-model="email" type="text" placeholder="Email">
<button ng-click="addContact()">Add contact</button>
<div>{{contactsController.name}}</div>
<div>
<ul>
<li ng-repeat="contact in contacts">
<div>{{contact.name}}</div>
<div>{{contact.email}}</div>
<div><button ng-click="deleteContact($index)">delete</button></div>
<div><button ng-click="editContact($index)">Edit</button></div>
</li>
</ul>
<input type="text" value="{{editContact.name}}"/>
<input type="text" value="{{editContact.email}}"/>
<button ng-click="changeValue(ii)">Edit</button>
</div>
</div>
<script>
// Your code goes here.
// $( document ).ready(function() {
// alert('jQuery asdfas!');
// Your code here.
// });
function contactsController($scope){
$scope.contacts=[{name:'asdf',email:'asdf'},
{name:'yweuir',email:'xcvzx'}
];
contactsController.prototype.addContact =function(){
console.log(this.name);
console.log(this.email);
this.contacts.push({name:this.name,email:this.email});
}
$scope.changeValue=function(){
$scope.contacts[$scope.ii]=$scope.editContact;
}
$scope.editContact=function(i){
$scope.editContact=$scope.contacts[i]
$scope.ii=i;
}
}
</script>
</body>
</html>
First, in the DOM always bind attributes for input boxes with ngModel. Example:
<input type="text" ng-model="editContact.name"/>
Second, never use $index as a point of reference for finding things in your controller. You should use the object itself. Example:
<li ng-repeat="contact in contacts">
<button ng-click="editSomeContact(contact)"></button>
</li>
Then your JavaScript should look like this:
$scope.addContact = function() {
$scope.contacts.push({name: '', email: ''});
};
$scope.editSomeContact = function(contact) {
$scope.editContact = contact;
};
$scope.deleteContact = function(contact) {
var index = $scope.contacts.indexOf(contact);
if(index > -1) {
$scope.contacts.splice(index, 1);
}
if($scope.editContact === contact){
$scope.editContact = null;
}
};
At this point, you don't need a changeValue function because you'll see that the contacts in the list will update with the edited fields due to the fact that the values are dynamically bound in both places.

Resources