AngularJS Setting default SELECT values - angularjs

Basic 'shopping cart' scenario.Users should be choosing their desired products in a form environment. Every product has a core price and multiple additional options available which change the price when selected.
Products and options are shown in two SELECT fields which are getting populated like this:
$scope.products = [
{
name:'Product A',
cost:5,
options: [{name:"Option 1", value:10}]
},
{
name:'Product B',
cost:10,
options: [{name:"Option 1", value:10},{name:"Option 2", value:15}]
}
];
$scope.cart = {
items: [{
qty: 1,
}]
};
and
<tr ng:repeat="item in cart.items">
<td>
<div class="type-select">
<select ng-model="item.product" ng-options="p.name for p in products"></select>
</div>
</td>
<td>
<div class="type-select">
<select ng-model="item.option" ng-options="o for o in item.product.options.name" ng- disabled="!checked">
</div>
</td>
<td>
<input ng:model="item.qty" value="1" size="4" ng:required="" ng:validate="integer" class="ng-pristine ng-valid ng-valid-required input-mini">
</td>
<td>
{{calculate()}}
</td>
</tr>
How can i set default value for the cart items?

You can have a watch on items.
As soon as an item is added, you should assign that item's product to be the first product. Something like that:
$scope.$watchCollection('cart.items', function(newValue, oldValue){
var changedItem = newValue[newValue.length-1];
changedItem.product = $scope.products[0];
});
Of course, that would be assuming you know that $scope.products is an array and that it is not empty. You can have some checks for that. Anyway, I think it is weird to have default values for that but there is a way for you.

Related

Angular JS: Show the Input value as Selected in Dropdown

I am newbie to Angular JS. I did find for the solution, but didn't resolved it.
As per selected value in dropdown, value should be displayed in corresponding Input box.
For Eg: If Basic is selected, corresponding value i.e 299 should be displayed in ng-model item.rate
If Advanced is selected, Corresponding value i.e. 499 should be displayed in ng-model item.rate.
HTML:
<tbody>
<tr ng-repeat="item in invoice.items ">
<td><select ng-model="item.names" ng-options="c.name for c in invoice.items track by c.id"></select></td>
<td><input type="text" ng-model="item.rate"/></td>
</tr>
</tr>
</tbody>
Angular JS:
$scope.invoice = {
items: [{id:1,name:'Basic',rate:299},
{id:2,name:'Advanced',rate:499}
]};
My Code is not working.I am unable to find out the Problem.Please help me.Thanks in advance.
you can use ngOptions full syntax value as text for item in items to bind the options with item.rate, see documentation.
ng-options="c.rate as c.name for c in invoice.items track"
Also I recommend you to avoid binding item.name to select and binding an extra filed to avoid conflicts.
refer below example.
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.selectedItem = '';
$scope.invoice = {
items: [{
id: 1,
name: 'Basic',
rate: 299
},
{
id: 2,
name: 'Advanced',
rate: 499
}
]
};
$scope.show = function(item) {
return item.name + '(' + item.rate + ')';
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select ng-model="selectedItem" ng-options="c.rate as c.name for c in invoice.items"></select></td>
<td><input type="text" ng-model="selectedItem" />
</div>

Bug while using ngRepeat. Set checkboxes and radio buttons checked in a wrong way

I have an array of users in the controller of the component. I've tried to print it using ngRepeat directive. There're following bugs in the final result:
According to array of users there should be the only one with checked active (the second).
There should be the second radio button checked instead of the third one.
I have the following list of users' objects:
$scope.users = [
{
id: 1,
name: 'John',
birthday: '06.07.2008',
city: 'Budapest',
active: false,
boss: false
},
{
id: 2,
name: 'Mary',
birthday: '01.02.2003',
city: 'Berlin',
active: true,
boss: true
},
{
id: 3,
name: 'James',
birthday: '04.05.2006',
city: 'Vienna',
active: false,
boss: false
}
];
Functions that check both statuses of each user:
$scope.isActive = function (id) {
return $scope.users[id].active;
}
$scope.isBoss = function (id) {
console.log(id);
return $scope.users[id].boss;
}
The actual template(view):
<tbody>
<div>
<tr ng-click="goToProfile(user.id)" ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.birthday}}</td>
<td>{{user.city}}</td>
<td>
<input type="checkbox" name="active" ng-checked="{ checked: isActive($index) }">
<h1>{{isActive($index)}}</h1>
</td>
<td>
<input type="radio" name="boss" ng-checked="{ checked: isBoss($index) }">
<h1>{{isBoss($index)}}</h1>
</td>
</tr>
</div>
</tbody>
I've done some test prints to make sure that it reads needed fields correctly. The actual result you can see on the screenshot and in the code. Thanks in advance!
You're using
$scope.users[id]
to access the user with a given id. But what you pass is not an id. It's an index. That makes your code confusing. You should pass the user itself, instead of its index. And in fact, you don't even need these functions at all, since you can just just user.active, and user.boss.
You don't need ng-checked either. Just use ng-model
<tr ng-click="goToProfile(user)" ng-repeat="user in users">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.birthday }}</td>
<td>{{ user.city }}</td>
<td>
<input type="checkbox" name="active" ng-model="user.active">
<h1>{{ user.active }}</h1>
</td>
<td>
<input type="checkbox" name="boss" ng-model="user.boss">
<h1>{{ user.boss }}</h1>
</td>
Note that I changed the radio to a checkbox, since two of your users are bosses, and it thus not make much sense to use a radio button.
If you want a radio button, then the model should be adapted; you should have an attribute in the scope referencing the unique user being the boss:
$scope.model = {
boss: $scope.users.filter(function(user) {
return user.boss;
})[0]
};
and in your view:
<input type="radio" name="boss" ng-model="model.boss" ng-value="user"/>
You set a name to the radio button, that made them part of the same group, which did not allow multiple radio buttons to be checked at the same time.
In addition, ng-checked should receive an expression, in this case the function call.
The following code suits your needs.
<tr ng-click="goToProfile(user.id)" ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.birthday}}</td>
<td>{{user.city}}</td>
<td>
<input type="checkbox" name="active" ng-checked="isActive($index)">
<h1>{{isActive($index)}}</h1>
</td>
<td>
<input type="radio" ng-checked="isBoss($index)">
<h1>{{isBoss($index)}}</h1>
</td>
</tr>
You could simply use ng-model="user.active" in the checkbox. No functions needed.
The same goes for the input radio.
Hope this helps. Check out the angular documentation for inputs.

What triggers a function call in other column when ngmodel changes in first column?

Consider the snippet:
JS
var mod = angular.module('module', []);
mod.controller('controller', function($scope) {
$scope.items = [{
id: 1,
label: 'aLabel',
subItem: {
name: 'aSubItem'
}
}, {
id: 2,
label: 'bLabel',
subItem: {
name: 'bSubItem'
}
}]
$scope.getValue = function(ngmodel) {
// some code goes here...
}
});
HTML
<body ng-controller='controller'>
<div>
<table>
<tr ng-repeat='count in counter'> // 5 times
<td>
<select ng-options="item.id as item.label for item in items"
ng-model="selected[$index]">
</select>
</td>
<td>
{{getValue(1)}}
</td>
<td>
</td>
</tr>
</table>
</div>
</body>
As soon as I select some value from the dropdown (select tag) in the first column, I notice that the function in the second column is triggered? What is the reason for this? What exactly is happening behind the scenes?
The reason is you are doing it inside ng-repeat
<tr ng-repeat = 'count in counter'>
You need to pass the object on the controller, in order to do some action on the same.
{{getValue(obj)}}

How to remove object from array within ng-repeat with AngularJS?

I am having an array with objects like [{...}, {...}] which I am outputting with ng-repeat. Then I have a delete button with a function to delete it.
Is there a simple way to delete it in AngularJS, perhaps with $index? Or I need to specify an ID on every object as an property?
If you don't apply a filter to reorder or filter your array, you can do this:
<div ng-repeat="item in items" ng-click="delete($index)">{{item}}</div>
And the delete function:
$scope.items = [...];
$scope.delete = function (index) {
$scope.items.splice(index, 1);
}
Another way to do it without filter problems: (ONLY IE9+)
<div ng-repeat="item in items | orderBy: 'id'" ng-click="delete(item)">{{item}}</div>
And the delete function:
$scope.items = [...];
$scope.delete = function (item) {
$scope.items.splice($scope.items.indexOf(item), 1);
}
http://jsfiddle.net/oymo9g2f/2/
Here is another example, using Jade too:
template.jade:
label All Items
ul.list-group
li.list-group-item(ng-repeat="item in items | orderBy: '_id'")
strong {{item.name}}
a.trash(ng-click='deleteItem(item)')
//a.trash is a bootstrap trash icon, but you don't need to use it.
controller.js:
$scope.deleteItem = function (item) {
$scope.items.splice($scope.items.indexOf(item),1);
}
removeWith
comparison for each element in a collection to the given properties object,
returning an array without all elements that have equivalent property values.
$scope.collection = [
{ id: 1, name: 'foo' },
{ id: 1, name: 'bar' },
{ id: 2, name: 'baz' }
]
<tr ng-repeat="obj in collection | removeWith:{ id: 1 }">
{{ obj.name }}
</tr>
<tr ng-repeat="obj in collection | removeWith:{ id: 1, name: 'foo' }">
{{ obj.name }}
</tr>
First try to do it this way, but the listing was not actualized at runtime.
$scope.delete = function (index) {
delete $scope.items[index];
}
Then with the answer given above by Facundo Pedrazzini did work properly for me.
$scope.delete = function (index) {
$scope.items.splice(index, 1);
}
Version: AngularJS v1.6.4
In blade.php
<table style="width:100%;">
<tr ng-repeat="name in planFormData.names track by $index">
<td>
<div class="form-group">
<label>Plan Name<span style="color:red;">*</span> </label>
<input type="text" class="form-control" ng-model="planFormData.names[$index].plan_name" name="plan_name" id="status-name" placeholder="Plan Name" autocomplete="off" required>
</div>
</td>
<td>
<i class="icon-plus" ng-click="addRow($index)" ng-show="$last"></i>
<i class="icon-trash" ng-click="deleteRow($event,name)" ng-show="$index != 0"></i>
</td>
</tr>
</table>
In controller.js
$scope.deleteRow = function($event, name) {
var index = $scope.planFormData.names.indexOf(name);
$scope.planFormData.names.splice(index, 1);
};
In Angular 6, I did similar for Multi Dimensional Array. It's working
RemoveThisTimeSlot(i: number, j: number) {
this.service.formData.ConsultationModelInfo.ConsultationWeekList[i].TimeBlockList.splice(j, 1);
}

Select All directive in AngularJS

I am using Checklist model directive with my App. I have issue, if -
I click select all button though it write up the array but its not
selecting checkbox. Same issue with Uncheck All though it empty the
model but it doesn't uncheck checkboxes.
If I select 2 or 3 randomly checkbox and click Select All Button it doesn't select All check-boxes.
Though its writing values to pushArray. But issues are checking and unchecking checkboxes.
$scope.items = [{id:1, name:"abc"},{id:2, name:"def"},{id:3, name:"ghi"}];
$scope.pushArray = [];
<table>
<tr ng-repeat="e in items">
<td class="text-right">
{{e.id}}
<input type="checkbox" checklist-change="imChanged()" checklist-model="pushArray" checklist-value="e.id" >
</td>
</tr>
</table>
I think you are pushing the complete list of object which is wrong. You just need to map the list and pass the id to the $scope
Edit: Works fine when you use $scope.pushArray as an object instead of array.
Working Plnkr
HTML
<body ng-controller="selection">
<table>
<tr ng-repeat="e in items">
<td>
<input type="checkbox" checklist-model="pushArray.ids" checklist-value="e.id"> {{e.name}}
</td>
</tr>
</table>
{{pushArray.ids | json}}
<br />
<button ng-click="select_all();">Select All</button>
<button ng-click="unselect_all();">Unselect All</button>
</body>
JS
var app = angular.module('app', ["checklist-model"]);
app.controller('selection', ['$scope', function($scope) {
$scope.items = [{
id: 1,
name: "abc"
}, {
id: 2,
name: "def"
}, {
id: 3,
name: "ghi"
}];
$scope.pushArray = { ids: []}; // Works fine when using it as an object
//$scope.pushArray = [];
$scope.select_all = function() {
$scope.pushArray.ids = $scope.items.map(function(item) { return item.id; });
};
$scope.unselect_all = function() {
$scope.pushArray.ids = [];
};
}]);
Hope it works for you!
I updated the examples on checklist-model and fix this issue. Check them out http://vitalets.github.io/checklist-model/

Resources