Single selecting an item on a table - javascript

So I have a table of items and when I click on a row the row gets selected. I've uploaded a demo here: http://plnkr.co/edit/m0TgTAQqITDIibMz7C4w?p=preview
The question is how do I make me able to select items one at a time and the previous active item get deselected? I also have a problem with the edit and remove menu on how to only show it when an item is selected since they have to be placed outside the controller area.
<nav class="navbar navbar-default" role="navigation">
<ul ng-show="true" class="nav navbar-nav">
<li>Remove</li>
<li>Edit</li>
</ul>
</nav>
<table ng-controller="PersonController" class="table">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr ng-repeat="person in people" ng-click="selectPerson(person)" ng-class="{active: person.selected }">
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
</tr>
</table>
<script>
function PersonController($scope) {
$scope.people = [
{ name: 'adam', age: 240 },
{ name: 'steve', age: 30 }
];
$scope.selectPerson = function(person) {
person.selected = true;
};
}
</script>

For your first question about multiple selects, you could cache the last selected item in the scope when selectPerson is called, then deselect it next time selectPerson is called by saying lastPerson.selected = false. Example:
function PersonController($scope) {
$scope.people = [
{ name: 'adam', age: 240 },
{ name: 'steve', age: 30 }
];
$scope.lastPerson = null;
$scope.selectPerson = function(person) {
person.selected = true;
if($scope.lastPerson) {
$scope.lastPerson.selected = false;
}
$scope.lastPerson = null;
$scope.lastPerson = person;
};
}
I would recommend moving the Edit/Remove menu into a Service, then you can access it globally from any controller & alter it's behavior. Example:
<!-- HTML -->
<div ng-controller="MenuCtrl" class="menu-parent">
<div ng-show="!isCollapsed" class="menu-container">
<!-- menu goes here -->
</div>
</div>
// controller
function MenuCtrl($scope, menuService) {
$scope.isCollapsed = true;
$scope.menuService = menuService;
$scope.$watch('menuService.menuCollapsed', function(newVal, oldVal, scope) {
$scope.isCollapsed = menuService.menuCollapsed;
});
}
// service
angular.service('menuService', function () {
return {
menuCollapsed: false
};
});
// example usage in any controller
function RandomCtrl($scope, menuService) {
$scope.randomEvent = function() {
menuService.menuCollapsed = true;
}
}
I would be happy to help you live here, if you'd like: https://www.sudonow.com/session/52699424ea4032693f000071

Related

How do I toggle a knockout foreach div individually without adding more html?

I used the foreach method to create markup foreach item in an observable array to create a treeview.
output example
category name1
content
content
category name 2
content
content
when I click on the category name I want just its content to show/hide, currently when I click on the category name it shows and hides all the categories.
var reportFilters = [
{ Text: "Campaign", Value: primaryCategories.Campaign },
{ Text: "Team", Value: primaryCategories.Team },
{ Text: "Agent", Value: primaryCategories.Agent },
{ Text: "List", Value: primaryCategories.List },
{ Text: "Inbound", Value: primaryCategories.Inbound },
{ Text: "Daily", Value: primaryCategories.Daily },
{ Text: "Services", Value: primaryCategories.Services },
{ Text: "Occupancy", Value: primaryCategories.Occupancy },
{ Text: "Data", Value: primaryCategories.Data }
];
self.showCategory = ko.observable(false);
self.toggleVisibility = function (report) {
var categoryName = report.PrimaryReportCategory;
var categoryContent = report.ID;
if (categoryName == categoryContent ) {
self.showCategory(!self.showCategory());
};
}
<div class="report-category-treeview" data-bind="foreach: $root.categories, mCustomScrollBar:true">
<ul class="column-list" >
<li class="report-category-heading" data-bind="click: $root.toggleVisibility"><span class="margin-top10" ><i class="fas fa-chevron-down"></i> <span class="report-category-name" data-bind="text: categoryName"></span></span></li>
<li id="panel" class="report-category-container" data-bind="foreach: reports, visible: $root.showCategory">
<div class="column-list-item" data-bind="click: $root.report_click, css: { 'selected': typeof $root.selectedReport() != 'undefined' && $data == $root.selectedReport() }">
<span class="column-list-text" data-bind="text: ReportName"></span>
</div>
</li>
</ul>
</div>
currently, when I click on the category name, it shows and hides all the
categories.
It's because showCategory is your single observable responsible for showing\hiding. What you really want is one show\hide observable per category.
I'm not sure how your entire data model looks like, but since you specifically asked about categories, then you should create a category view model, and probably some container view model, which I'll name here master:
var categoryVM = function (name) {
var self = this;
self.name = ko.observable(name);
self.isVisible = ko.observable(false);
self.toggleVisibility = function () {
self.isVisible(!self.isVisible());
}
// ... add here your other observables ...
}
// name 'masterVM' whatever you like
var masterVM = function () {
var self = this;
self.categories = ko.observables([]);
// ... probably add here other observables, e.g. 'reports' ...
self.init = function (rawCategories) {
rawCategories.forEach(function (item) {
categories.push(new categoryVM(item.name)); // replace 'name' with your property
}
}
}
var master = new masterVM();
master.init(getCategories()); // pass in your categories from wherever they come from
ko.applyBindings(master);
Then, in your html, this would be your outer foreach:
<div class="report-category-treeview" data-bind="foreach: categories ... />
and your lis (for brevity, I'm ommiting nested tags under your lis):
<li class="report-category-heading"
data-bind="click: toggleVisibility">
<li id="panel" class="report-category-container"
data-bind="foreach: $root.reports, visible: isVisible">

Array vs Single Object - AngularJS / Javascript (Basic)

I have a very basic array
[
{
ticketId: 1,
name: "John",
},
{
ticketId: 124,
name: "Ads"
}
]
I show the data in the select
<ul class="dropdown-menu">
<li ng-repeat="ticket in tickets">
{{ticket.ticketId}}
</li>
</ul>
But how do I use the data from the selected ticket from another place in my code
like
<tr>
<th>Name</th>
<td>{{???}}</td>
</tr>
Controller
$http.get(ticketAPIBaseUrl + '/tickets/' + customerNumber,
{withCredentials: false}).then(response => {
console.log(response);
vm.tickets = response.data;
}, error => {
console.log(error);
});
You can use to that filter like so:
HTML:
<input type="number" ng-model="tick"/>
<table>
<tr ng-repeat="ticket in tickets | ticketFilter:tick">
<td>{{ticket.name}}</td>
<td>{{ticket.ticketId}}</td>
</tr>
</table>
JS:
app.filter('ticketFilter', function(){
return function(data, tick){
if (!tick) return data;
var ticketItems = [];
angular.forEach(data, function(item){
if(item.ticketId == tick) {
ticketItems.push(item);
}
});
return ticketItems;
};
})
plunker: http://plnkr.co/edit/q2ixIBCm9tfUW0c2V1BC?p=preview
Use the ng-click directive:
<ul class="dropdown-menu">
<li ng-repeat="ticket in tickets">
<a ng-click="selected=ticket">{{ticket.ticketId}}</a>
</li>
</ul>
Then display the selected item:
<tr>
<th>Name</th>
<td>{{selected.name}}</td>
</tr>
For more information, see AngularJS ng-click Directive API Reference.

Angular 1 ng-if not displaying div

I've been writing a code that uses ng-if to display a div with a message if an array is empty([]). The ng-if isn't displaying the div even though I have console.log the array and it shows up empty.
I am still new to angularjs so I am not sure if I am using the ng-if directive correctly. Here is my code, anything helps, thank you!
js:
(function () {
'use strict';
var data = [];
var shoppingList = [
{
name: "Donuts",
quantity: "10"
},
{
name: "Cookies",
quantity: "10"
},
{
name: "Drinks",
quantity: "10"
},
{
name: "Shrimp",
quantity: "10"
},
{
name: "Ice Cream tub",
quantity: "100"
}
];
console.log(data);
angular.module('shoppingListCheckOffApp', [])
.controller('toBuyListController', toBuyListController)
.controller('boughtListController', boughtListController)
.service('shoppingListService', shoppingListService);
toBuyListController.$inject = ['shoppingListService'];
function toBuyListController(shoppingListService) {
var buy = this;
buy.shoppingList = shoppingList;
buy.shoppingListBought = function (itemIndex) {
shoppingListService.dataTransfer(buy.shoppingList[itemIndex].name, buy.shoppingList[itemIndex].quantity);
shoppingListService.remove(itemIndex);
};
}
boughtListController.inject = ['shoppingListService'];
function boughtListController(shoppingListService) {
var bought = this;
bought.data = shoppingListService.getData();
console.log(bought.data);
}
function shoppingListService() {
var service = this;
service.dataTransfer = function (itemName, quantity) {
var item = {
name: itemName,
quantity: quantity
};
data.push(item);
}
service.remove = function (itemIndex) {
shoppingList.splice(itemIndex, 1);
};
service.getData = function () {
return data;
};
};
})();
html:
<!doctype html>
<html ng-app="shoppingListCheckOffApp">
<head>
<title>Shopping List Check Off</title>
<meta charset="utf-8">
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div>
<h1>Shopping List Check Off</h1>
<div>
<!-- To Buy List -->
<div ng-controller="toBuyListController as buy">
<h2>To Buy:</h2>
<ul>
<li ng-repeat="item in buy.shoppingList">Buy {{item.quantity}} {{item.name}}(s)<button
ng-click="buy.shoppingListBought($index);" ng-click="myVar = true"><span></span>
Bought</button></li>
</ul>
<div ng-if="buy.shoppingList === []">Everything is bought!</div>
</div>
<!-- Already Bought List -->
<div ng-controller="boughtListController as bought">
<h2>Already Bought:</h2>
<ul>
<li ng-repeat="item in bought.data">Bought {{item.quantity}} {{item.name}}(s)</li>
</ul>
<div ng-if="bought.data === []">Nothing bought yet.</div>
</div>
</div>
</div>
</body>
</html>
You should use ng-if (for arrays) in this way:
<div ng-if="!bought.data.length">Nothing bought yet.</div>
This will show the message when the list is empty.
If you do this:
buy.shoppingList === []
You are comparing you buy.shoppingList array with a new empty array, then it will return false.

Angular ng-repeat change values

I'm doing a table with angular using ng-repeat. And all it's work but in some cases the json return me some data like PA-AC-DE and i want to change this in the table in Pending, Active and deactivate. And i don't know how i can do it.
<table class="table table-bordered table-hover table-striped dataTable no-footer" data-sort-name="name" data-sort-order="desc">
<tr role="row" class="info text-center">
<th ng-click="order('msisdn')">Número Teléfono</th>
<th ng-click="order('icc')">ICC</th>
<!--th>IMEI</th-->
<th ng-click="order('ActivationStatus')">Estado</th>
<th ng-click="order('sitename')">Instalación</th>
<th ng-click="order('siteaddress')">Dirección</th>
<th ng-click="order('sitecity')">Ciudad</th>
<th ng-click="order('sitezip')">Código Postal</th>
<th ng-click="order('phonedesc')">Modelo Teléfono</th>
<th ng-click="order('ContractingMode')">VBP</th>
</tr>
<tr class=" text-center" ng-repeat-start="object in filteredsites = (objects | filter:searchText) | filter:tableFilter| orderBy:predicate:reverse" ng-click="showDetails = ! showDetails">
<td>{{object.msisdn}}</td>
<td>{{object.icc}}</td>
<td>{{object.ActivationStatus}}</td>
<td>{{object.sitename}}</td>
<td>{{object.siteaddress}}</td>
<td>{{object.sitecity}}</td>
<td>{{object.sitezip}}</td>
<td>{{object.phonedesc}}</td>
<td>{{ object.ContractingMode ? 'Yes': 'No'}}</td>
</tr>
</table>
You can use a filter
{{object.ActivationStatus | statusFilter}}
and statusFilter will be like:
angular.module('module', []).filter('statusFilter', function() {
return function(input) {
//switch-case
};});
You could use ng-show to show text depending on the value returned from your API like so:
<td><span ng-show="object.ActivationStatus=='AC'">Active</span><span ng-show="object.ActivationStatus=='PA'">Other Label</span></td>
and so on.
With a custom filter method it would look like in the demo below or here at jsfiddle.
But also a getter function with the same code would be OK.
angular.module('demoApp', [])
.controller('mainController', function() {
this.data = [
{status:'AC'},
{status:'AC'},
{status:'DE'},
{status:'PA'},
];
})
.filter('filterStatus', function() {
var labels = {
AC: 'active',
DE: 'deactive',
PA: 'pending'
};
return function(input) {
return labels[input];
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as ctrl">
<ul>
<li ng-repeat="row in ctrl.data">
status: {{row.status | filterStatus}}
</li>
</ul>
</div>
Based on AWolf answer with filter, here is using a function in the controller:
http://jsfiddle.net/f4bfzjct/
angular.module('demoApp', [])
.controller('mainController', function() {
var vm = this;
vm.data = [
{status:'AC'},
{status:'AC'},
{status:'DE'},
{status:'PA'},
];
vm.getFullStatus = function(value) {
var labels = {
AC: 'active',
DE: 'deactive',
PA: 'pending'
};
return labels[value];
}
});
<div ng-app="demoApp" ng-controller="mainController as ctrl">
<ul>
<li ng-repeat="row in ctrl.data">
status: {{ctrl.getFullStatus(row.status)}}
</li>
</ul>
</div>
I think you should create a filter in your module:
ngModule.filter('phoneNumberStatus', function() {
statuses = {
AC: 'Active'
DE: 'Unactive'
}
return function(value) {
return statuses[value] || "Unknown"
}
})
and then use it in your template:
<td>{{ object.ActivationStatus | phoneNumberStatus }}</td>
This way will enable you to reused this filter in any template, avoiding duplicated code.
You can create a javascript function that returns your desired value:
$scope.getFullActivationText = function(input) {
if (input === 'PA') {
return 'Pending';
}
else if (input === 'AC') {
return 'Active';
}
else if (input === 'DE') {
return 'Deactivate';
}
}
Now you can keep everything the same in your HTML but replace:
<td>{{object.ActivationStatus}}</td>
into
<td>getFullActivationText(object.ActivationStatus)</td>

Assign ng-model to checkbox if some value == anothervalue

I have a User object in Angular controller. I also have an array of Account objects with respective ID for each.
In User I have a field "default_account" where I want to put ID of a default account. So, user can have a lot of accounts but only one of them can be default. When I go to Account options, I have a checkbox there which is responsible for setting/unsetting the account as default.
Now I want to set checkbox on/off depending on its being default for the user. And I also need to respectively change default_account field inside User object on checkbox change. It puzzles me quite much how I can do it.
Any advice is appreciated!
Very approximate (didn't text that):
html:
<div ng-repeat="account in accounts">
<input type="checkbox" ng-checked="account == user.default_acount"
ng-click="SelectAssDefault(account )" />
</div>
js:
function MyCtrl($scope) {
$scope.user = { name: 'user', default_acount: null};
$scope.accounts = [{ }, { }, ...];
$scope.SelectAssDefault = function (account) {
$scope.user.default_acount = account;
};
}
EDIT: a working example: http://jsfiddle.net/ev62U/120/
If you want to set a checkbox to true based on a variable, you can set ng-checked="variable" within the input tag.
If the variable is true the box will be checked. If it's false it won't. Alternatively, an expression will also work e.g. ng-checked="1===1" will evaluate to true.
If you want to alter something else based on user clicking on the checkbox, set ng-click="someCtrlFunction()" within the input tag. This will call a function in your controller. You can look up the value of the checkbox from your controller if you've bound to it.
Here's a fiddle: http://jsfiddle.net/E8LBV/10/ and here's the code:
HTML
<div ng-app="App">
<div ng-controller="AppCtrl">
<ul>
<li ng-repeat="user in users">{{user.name}}
<ul>
<li ng-repeat="account in user.accounts">
<input type="checkbox" ng-model="checked" ng-checked="account == user.default" ng-click="changeDefault(user.id,account,checked)">{{account}}</input>
</li>
<ul/>
</li>
</ul>
</div>
</div>
JS
var app = angular.module('App', []);
app.service('Users', function () {
var Users = {};
Users.data = [{
'id': 1,
'name': 'jon',
'default': null
}, {
'id': 2,
'name': 'pete',
'default': null
}];
return Users;
});
app.service('Accounts', function () {
var Accounts = {};
Accounts.data = [{
'user': 1,
'ac': 123456
}, {
'user': 2,
'ac': 456832
}, {
'user': 2,
'ac': 345632
}, {
'user': 1,
'ac': 677456
}];
return Accounts;
});
app.controller('AppCtrl', function ($scope, Users, Accounts) {
$scope.users = Users.data;
//attach accounts to user
for (i = 0; i < $scope.users.length; i++) {
$scope.users[i].accounts = [];
for (ii = 0; ii < Accounts.data.length; ii++) {
if (Accounts.data[ii].user == $scope.users[i].id) {
$scope.users[i].accounts.push(Accounts.data[ii].ac);
}
}
}
//function to change the default account for the user
$scope.changeDefault = function (id, account, checked) {
if (!checked) {
return;
}
for (i = 0; i < $scope.users.length; i++) {
if ($scope.users[i].id == id) {
$scope.users[i].
default = account;
}
}
}
});
Here is my solution that perfectly worked for me!
<tbody ng-repeat="account in accounts">
<tr>
<td ><a ng-click="getloandetails(account.idAccount)">{{account.accountName}}</a></td>
<td>$ {{account.currentBalance}}</td>
</tr>
</tbody>
and in Angular side just do this:
$scope.getloandetails = function(accountId) {
alert('Gettring details for the accountId: ' + accountId);
};

Categories

Resources