How to checked check box in angular js? - angularjs

I have two list (List 1 and List 2) of check box in which three items
available in both list. My problem is when I checked on list 1 item
then list 2 item also checked not sure why. I need to stop this. My
requirement is when I checked list 1 item then it does not affect
List 2 item. Please help
Fiddle Here
VIEW
<div ng-app="checkbox" ng-controller="homeCtrl">
<div ng-repeat="item in list">
<input type="checkbox" ng-model="item.checked"
ng-click="fnChangeAssetType1(item)" />
<label>{{item.value}}</label>
</div>
<br/><br/>
New List<br/><br/>
<div ng-repeat="items in lists">
<input type="checkbox" ng-model="items.checked"
ng-click="fnChangeAssetType(items)" />
<label>{{items.value}}</label>
</div>
</div>
JS
var app = angular.module('checkbox', []);
app.controller('homeCtrl', function($scope) {
var list = [{
"id": 1,
"value": "apple",
}, {
"id": 3,
"value": "orange",
}, {
"id": 5,
"value": "pear"
}];
$scope.list=list;
$scope.lists=list;
$scope.fnChangeAssetType = function (items) {
angular.forEach($scope.lists, function (item) {
item.checked = false;
});
items.checked = true;
};
$scope.fnChangeAssetType1 = function (items) {
angular.forEach($scope.list, function (item) {
item.checked = false;
});
items.checked = true;
};
});

This is because your $scope.list & $scope.lists both are pointing to same array in the memory because of array (list) is a reference type. what u need to do is create a separate array for $scope.lists as below.
you need to use angular.copy()
$scope.list=list;
$scope.lists= angular.copy(list); // this will create a deep copy of list array and store it in another memory slot, //refer the angular.copy doc
here is the updated fiddle

Related

Store the value of selection from dropdown to a variable AngularJS

I would like to store the value of a selection from a dropdown in AngularJS.
I am able to replicate the new selection on UI but not in console.
<div ng-controller="MyCtrl">
<div>
Fruit List:
<select id="fruitsList"
ng-model="cart"
ng-change="getSelectedLocation()"
ng-options="state for state in shelf"></select>
<br/>
<tt>Fruit selected: {{cart}}</tt>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.cart = "";
$scope.shelf = ['Banana', 'Apple', 'Pineapple', 'Blueberry'];
$scope.getSelectedLocation = function() {
console.log($scope.cart);
}
$scope.printSelectedValue = function() {
if ($scope.cart == 'Banana') {
console.log("Its a banana")
} else if ($scope.cart == "Apple") {
console.log("Its an apple")
} else {
console.log("Its neither a banana nor an apple")
}
}
});
Any idea on how to achieve that?
jsfiddle link
You're printing the cart once, when the controller is instanciated. At that time, the user hasn't had the chance to select anything yet.
If you want to print the selection every time it changes, use ng-change (you're already using it, BTW):
ng-change="printSelection()"
and in the controller:
$scope.printSelection = function() {
console.log($scope.cart);
};

How to Implement ng-model inside ng-repeat for mutilpe textfields in AngularJs?

This is my code
function Ctrl($scope) {
$scope.data = [];
$scope.data = [{
"label": "name",
"type": "string"
}, {
"label": "email",
"type": "string"
}];
$scope.addFields = function() {
var count = 0;
angular.forEach($scope.data, function(obj) {
if (count == 2) {
return true;
}
$scope.data.push(obj);
count = count + 1;
});
};
$scope.save = function() {
console.log($scope.data);
};
}
<div ng-app>
<div ng-controller="Ctrl">
<input type="button" value="add" ng-click="addFields()" />
<div ng-repeat="eachItem in data">
<label>{{eachItem.label}}</label>
<input type="text" ng-model="eachItem.value" />
</div>
<input type="button" value="save" ng-click="save()" />
</div>
</div>
This is my jsFiddle http://jsfiddle.net/0c5p38dt/5/
In the above code i have an array with multiple objects, these objects are getting from services dynamically. when i click add button again same objects push to the same array. I use ng-model inside ng-repeat for textfield. But when i enter data that will be effect on other textfields also.So how to differentiate the ng-model value for multiple same objects in array.
Your addFields() function is not adding fields that have their own objects. It is creating new fields that point to the existing objects.
Essentially, when your addFields() is called, it is saying "add two new fields that point to the same object as the first two fields." This is why they all share the same model.
The solution is to actually create a new object that is a clone of the original in the addFields() function like so:
$scope.addFields = function () {
var count=0;
angular.forEach($scope.data,function(obj){
if(count==2){
return true;
}
// Create a new object with the same properties as the original
var newObj = {'label':obj.label, 'type':obj.type}
$scope.data.push(newObj);
count=count+1;
});
};
I modified your jsFiddle: http://jsfiddle.net/nhupL4gs/

angularjs - how to get in the controller the index of an item in a ng-repeat filter based on the value of one of its properties?

I use a ng-repeat in my html file to display filtered items:
<li ng-repeat="item in (filteredItems = (items | filter:query))">
{{ item.name }}
</a>
In the controller, I'd like to get the index of an item based on one of his property.
Precision: I'd like to get the index in the filtered list and not in the whole list.
Here for example, it will be the index of the item witch name is some_item_7.
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope',
function MyCtrl($scope) {
$scope.query = 'some';
$scope.items =
[
{ name: 'some_item_1' },
{ name: 'another_item_2' },
{ name: 'some_item_3' },
{ name: 'another_item_4' },
{ name: 'some_item_5' },
{ name: 'another_item_6' },
{ name: 'some_item_7' },
{ name: 'another_item_8' },
{ name: 'some_item_9' }
];
$scope.itemNext = function (item) {
console.log(item.name);
};
$scope.getIndexFromName = function (name) {
console.log("trying to get the index of the item with name = " + name);
}
$scope.getIndexFromName('some_item_7');
}
]);
http://plnkr.co/edit/C8gL9qV1MyonTwDENO9L?p=preview
Any idea ?
Your ng-repeat expression creates the filteredList array on your scope.
<li ng-repeat="item in (filteredItems = (items | filter:query))">
You can loop through it like any array, checking for the item matching the name parameter.
$scope.filteredItems
Here is a demo: http://plnkr.co/69nnbaZaulgX0odG7g7Y
See this related post: AngularJS - how to get an ngRepeat filtered result reference
Update
Your comments indicate that you don't want to wait for ng-repeat to create the array of filtered items. You can use the $filter service to easily initialize the same array before the page loads. Use:
$scope.filteredItems = $filter('filter')($scope.items, {name: $scope.query}, false)
Doing so does not interfere with ng-repeat saving its filter results to the same filteredItems array during DOM creation.
Here is an updated (and interactive) demo: http://plnkr.co/NSvBz1yWvmeFgXITutZF

Saving a checkbox list in Angularjs with node

I want to save and load a checkbox list using binding in angularjs with a node backend. This SO question (How do I bind to list of checkbox values with AngularJS?) answers how I can load the check box from a static javascript object but how can I save the checkbox values after the user selects them?
I want to save the checkbox values in a single field but how can I tell angular to bind the checkbox values into a single field defined in a model to my mongodb? I cant just use ng-model as there are multiple checkboxes.
Needless to say that I am new to angular so any help here is greatly appreciated ...
Thanks for any help you can provide.
kseudo
Just add ng-model to your checkbox. By this way you can update model in controller on any checkbox state change.
Here is example:
HTML
<div ng-controller="Ctrl">
<label ng-repeat="fruit in fruits">
<input
type="checkbox"
name="fruit.name"
ng-model="fruit.value"
> {{fruit.name}}
</label>
<pre>{{fruits| json}}</pre>
</div>
JS
var app = angular.module('app', []);
function Ctrl($scope) {
$scope.fruits = [{
name: 'apple',
value: false
}, {
name: 'orange',
value: false
}, {
name: 'pear',
value: false
}, {
name: 'naartjie',
value: false
}];
}
Demo Fiddle
[EDIT]
BTW we can make the copy by using angular.copy() method. When we press button, the new copy of fruits model will be created (and you should send it to server as json). Old model fruits will stay the same:
$scope.fruitsCopy = [];
$scope.init = function(){
$scope.fruitsCopy = angular.copy($scope.fruits );
}
To convert data to JSon I would use:
var jsonData = JSON.stringify($scope.fruitsCopy);
Demo2 Fiddle
Let's say you defined your model as such:
function Ctrl($scope) {
$scope.items = [{
name: 'A',
checked: false
}, {
name: 'B',
checked: false
}, {
name: 'C',
checked: false
}, {
name: 'D',
checked: false
}];
}
And created a view for the model:
<ul>
<li ng-repeat="item in items">
<label>
<input type="checkbox" ng-model="item.checked">
{{item.name}}
</label>
</li>
</ul>
<button ng-click="save()">save</button>
Next you have to define save function:
$scope.save = function() {
//angular.toJson converts array to string, something like
// '[{"name":"A","checked":false},{"name":"B","checked":true},...]'
var json = angular.toJson($scope.items);
//Service is angular service for your model that makes http requests to your backend
Service.save(json).then(function(){
//here you can notify user that data is persisted
}, function() {
//here you can notify user that there was a problem with request
});
}
And a simple model service:
.service('Service', function($http) {
return new function() {
this.save = function(data) {
return $http.post('url/to/backend', data);
}
}
});

Tracking current selected item with AngularJS

I'm new to AngularJS and can't find any suitable answer for this. My app currently consists of a list of items displayed via Angular. There is also a label which displays the name of the currently selected item, and an input box which allows the name of the currently selected item to be modified.
What I cannot figure out is how to simultaneously:
Allow the selection of an item, which triggers the update of the label and the input box text to display the name of the newly selected item
Allow editing of the name in the input box which triggers the update of the label displaying the currently displayed item name
Edits to the name should be reflected in the original model item
At the moment, i'm trying to keep track of which item is current via a flag against the item and this isn't doing what I want. Ideally I would replace currentItem in the below with a direct reference to the item in items with isCurrent=true.
Current item name label:
`<div id="CurrentItem" data-ng-model="currentItem">{{currentItem.name}}</div>`
Current item name input box:
`<input id="ItemName" type="text" data-ng-model="currentItem" value="{{currentItem.name}}" />`
Display all items:
<div data-ng-repeat="item in items" data-ng-click="changeItem(item)">`
<img src="images/ItemIcon.png">
<div>{{item.name}}</div>
Controller:
var CoreAppController = function($scope, $location) {
$scope.changeItem = function(item) {
var length = $scope.items.length;
while(length-- ) {
$scope.items[length].isCurrent = false;
}
$scope.currentItem = item;
$scope.items.indexOf(item).isCurrent = false;
}
$scope.createItem = function(name, layout) {
$scope.items.push({ id: $scope.items.length + 1,
name: name,
isCurrent: false
});
}
// Initialisation
$scope.items = [];
$scope.createItem("Item 1");
$scope.createItem("Item 2");
$scope.items[0].isCurrent = true;
$scope.currentItem = $scope.items[0];
}
Any advice appreciated!
I'm not sure about your current code, but here is a mock up that does what it appears you're requesting.
The JS
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ name: 'foo' },
{ name: 'bar' },
{ name: 'test' }
];
$scope.editing = null;
$scope.editItem = function(item) {
$scope.editing = item;
}
});
and the markup
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
{{item.name}}
<a ng-click="editItem(item);">edit</a>
</li>
</ul>
<div ng-show="editing">
<input type="text" ng-model="editing.name"/>
<span>{{editing.name}}</span>
</div>
</body>
Hopefully that helps. If you need more of a description, let me know.

Resources