Array vs Single Object - AngularJS / Javascript (Basic) - javascript

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.

Related

Filter by two fields in Angular.js

I have a code that filters through a field and marks the words that relate to the input search. I need this filtered me not only by the title, but also by the name. How can I modify the code so that when I write, I filter both title and name?
<li ng-repeat="item in data | filter:search.title"
ng-bind-html="item.title | highlight:search.title">
</li>
http://jsfiddle.net/sgo3wxwc/
you can send two or more options to filter by gathering them in object:
<li ng-repeat="item in data | filter:{title:search.title,name:search.name}"
ng-bind-html="item.title | highlight:search.title">
</li>
it's recommended to use filters in controller to avoid $digest cycle on them
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" placeholder="Search" ng-model="search.title">
<ul>
<!-- with filter -->
<li ng-repeat="item in data | filter:{title:search.title,name:search.name}"
ng-bind-html="item.title | highlight:search.title">
{{item}}
</li>
</ul>
</div>
script code is here:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.data = [
{ title: "Bad",name:'bill' },
{ title: "Good",name:'Goe' },
{ title: "Great",name:'Brad' },
{ title: "Cool",name:'yan' },
{ title: "Excellent",name:'mikle' },
{ title: "Awesome",name:'mosa' },
{ title: "Horrible",name:'morteza' },
]
}).filter('highlight', function($sce) {
return function(text, phrase) {
if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
'<span class="highlighted">$1</span>')
return $sce.trustAsHtml(text)
}
})

AngularJS Select from Json (similiar to MySQL)

I have a json:
{"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","url":"/account/deposit","selected":false},{"itemTitle":"Withdrawal","url":"/account/withdraw","selected":false},{"itemTitle":"Edit Profile","url":"/account/editprofile","selected":false},{"itemTitle":"Change Password","url":"/account/changepassword","selected":false}]}
Now I just want to check if there is an item (child) inside sectionTitle where selected is true.
Something like this in SQL
SELECT * FROM sectionItems WHERE selected=true
Can I do something similar in angular js, so I can check if the the parents has children?
I hope you understood my question.
This is my html
<nav class="sidebar-nav">
<ul class="nav metismenu" id="side-menu-help">
<li ng-repeat="menuItem in accountCtrl.menuStructure">
<a class="{{ (menuItem.sectionItems.length > 0) ? 'metisHasChildren' : '' }}" href="/en/help-area/poker-help/poker-rules/">
<span ng-if="menuItem.sectionItems.length > 0" class="fa arrow fa fa-angle-double-down"></span>
{{ ::menuItem.sectionTitle }}
{{ ::menuItem }}
</a>
<ul class="nav nav-second-level collapse in">
<li ng-repeat="subMenuItem in menuItem.sectionItems" ng-click="accountCtrl.changePage(subMenuItem.url)">
<a ng-class="(subMenuItem.selected) ? 'page-active' : ''">{{ ::subMenuItem.itemTitle }}</a>
</li>
</ul>
</li>
</ul>
</nav>
You do not need to anything fancy to get this working. Simply convert the json to an object and access the property you want using dot notation. So for example:
var json = JSON.parse(json);
var selectedItems = [];
angular.forEach(json.sectionItems, function(sectionItem) {
if (sectionItem.selected) {
selectedItems.push(sectionItem);
}
});
Would convert the json string to an object and then loop over each sectionItem child, check for selected is true and create an array of matching items.
You can use a forEach loop. This example will return an array of all sectionItems where selected equals true, but you can return whatever you'd like.
$scope.items =[];
angular.forEach(sectionItems, function(item){
if (item.selected === true){
$scope.items.push(item);
}
})
UPDATE
Here's a working plunk
To make this work inline with ng-repeat you will use it in a filter, like this:
app.filter('menuFilter', function() {
return function(menuItems) {
var filtered = [];
angular.forEach(menuItems, function(menuItem) {
angular.forEach(menuItem.sectionItems, function(item) {
if (item.selected === true) {
filtered.push(menuItem);
}
});
});
return filtered;
}
});
And change your markup, like this:
ng-repeat="menuItem in accountCtrl.menuStructure | menuFilter "
First, you don't need to do any custom filter or anything like that, just use the standard filter, as below:
<li ng-repeat="menuItem in accountCtrl.menuStructure | filter: { sectionItems: { selected: true } }"> {{ menuItem.sectionTitle }}
Working demo:
angular.module('app', [])
.controller('accountController', function() {
var vm = this;
vm.menuStructure = [
{
"sectionTitle":"Account Information",
"sectionItems":[
{
"itemTitle":"Balance",
"url":"/account/balance",
"selected":true
},
{
"itemTitle":"Account Statement",
"url":"/account/statementsearch",
"selected":false
},
{
"itemTitle":"Deposit",
"url":"/account/deposit",
"selected":false
},
{
"itemTitle":"Withdrawal",
"url":"/account/withdraw",
"selected":false
},
{
"itemTitle":"Edit Profile",
"url":"/account/editprofile",
"selected":false
},
{
"itemTitle":"Change Password",
"url":"/account/changepassword",
"selected":false
}
]
},
{
"sectionTitle":"Account Information 2",
"sectionItems":[
{
"itemTitle":"Balance",
"url":"/account/balance",
"selected":false
},
{
"itemTitle":"Account Statement",
"url":"/account/statementsearch",
"selected":false
},
{
"itemTitle":"Deposit",
"url":"/account/deposit",
"selected":false
},
{
"itemTitle":"Withdrawal",
"url":"/account/withdraw",
"selected":false
},
{
"itemTitle":"Edit Profile",
"url":"/account/editprofile",
"selected":false
},
{
"itemTitle":"Change Password",
"url":"/account/changepassword",
"selected":false
}
]
}
];
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="accountController as accountCtrl">
<ul>
<li ng-repeat="menuItem in accountCtrl.menuStructure | filter: { sectionItems: { selected: true } }"> {{ menuItem.sectionTitle }}
<ul class="nav nav-second-level collapse in">
<li ng-repeat="subMenuItem in menuItem.sectionItems" ng-click="accountCtrl.changePage(subMenuItem.url)">
<a ng-class="{ 'page-active': subMenuItem.selected }" ng-bind="::subMenuItem.itemTitle"></a>
</li>
</ul>
</li>
</ul>
</body>
</html>
Tips:
Instead of using ngClass with ternary operator, you can simply use this way:
ng-class="{ 'page-active': subMenuItem.selected }"
Even if works in this way that you're using, I'd recommend you to take a look on the special-repeats, it fits really well in your situation.
I hope it helps!!
var JSONStr=[{"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","url":"/account/deposit","selected":false},{"itemTitle":"Withdrawal","url":"/account/withdraw","selected":false},{"itemTitle":"Edit Profile","url":"/account/editprofile","selected":false},{"itemTitle":"Change Password","url":"/account/changepassword","selected":false}]}];
var result = JSONStr.where({ selected: true });

Disabled Button when it Clicked in table

I want to disable button Assign when it clicked, bacause it should assign only once so i can achieve this, I have done the following code in HTML:
<table class="table details">
<thead>
<tr>
<th sort-by="firstName">User Name</th>
<th sort-by="lastName">Description</th>
<th sort-by="Budget" sort-init="desc">Bid Amount</th>
<th sort-by="lastName">Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="issue in issues | filter:filter">
<td><strong><a href="/ViewBid/Index?{{ issue.User_ID }}" />{{ issue.UserName }} </strong></td>
<td><a href="/ViewBid/Index?{{ issue.User_ID }}" />{{ issue.Description }}</td>
<td><a href="/ViewBid/Index?{{ issue.User_ID }}" />{{issue.Bid_amt}}</td>
<td>
<div ng-controller="ExampleCtrl_Assign">
<div ng-show="AsgHide">
<button type="button" ng-click="AssignRecord(issue.ID,issue.Description,issue.Bid_amt)">Assign</button>
</div>
</div>
<div ng-controller="ExampleCtrl_Delete">
<div ng-show="AsgHide" >
<button type="button" ng-click="DeleteRecord(issue.ID)">Delete</button>
</div>
</div>
</td>
</tr>
</tbody>
</table>
And JavaScript Code is as following:
var app = angular.module('siTableExampleApp_Assign', []);
app.controller('ExampleCtrl_Assign', ['$scope','$http', function ($scope, $http) {
var user2 = window.localStorage.getItem('UserId');
var Basic = window.localStorage.getItem('Basic');
var Token = window.localStorage.getItem('Token');
$scope.FunctionDisable = function (i) {
$("#rbutton'+i+'").attr("disabled", "disabled");
}
$scope.AssignRecord = function (ID, Description, Bid_amt) {
var BidID = ID;
var date = new Date();
encodedString = {
"ID": 1,
"Travel_Info_ID": travel_info_id,
"Bid_ID": parseInt(BidID),
"Description": Description,
"Bid_amt": Bid_amt,
"Status": "InProcess",
"User_ID": user2,
"Entry_Date": date,
"Update_Date": date
}
$http({
method: 'POST',
url: 'http://saisoftwaresolutions.com/v1/Assigned_Bids/Assigned_Bid/Create',
data: encodedString,
headers: {
'Authorization': 'Basic ' + Basic,
'Token': Token
}
})
.success(function (data, status, headers, config) {
console.log(headers());
console.log(data);
if (status === 200) {
//window.location.href = 'http://localhost:22135/BDetail/Index';
} else {
$scope.errorMsg = "Login not correct";
}
})
.error(function (data, status, headers, config) {
$scope.errorMsg = 'Unable to submit form';
})
Use can always use ng-disabled directive provided by Angular to disabled html elements.
I have made one example based on your requirements and help it will solve your issue:
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat="item in items">{{item.User_ID}}: {{item.User_Name}}
<button ng-click="handleClick($index)" ng-disabled="item.disabled">
{{item.User_Name}}
</button>
</li>
</ul>
</div>
function MyCtrl($scope) {
$scope.items = [
{
User_ID: '10',
disaled: false,
User_Name: 'ABC'
}, {
User_ID: '11',
disaled: false,
User_Name: 'XYZ'
}
];;
$scope.handleClick = function(index){
$scope.items[index].disabled = true;
}
}
Angular has a directive just for this: ng-disabled.
From their official documentation:
This directive sets the disabled attribute on the element if the
expression inside ngDisabled evaluates to truthy.
So you can set a boolean value in your code-behind to true and have that evaluate inside your button. For example:
<button type="button" ng-disabled="issue.IsDisabled" ng-click="AssignRecord(issue.ID,issue.Description,issue.Bid_amt)">Assign</button>
Also, check out the example in their documentation and this jsfiddle: https://jsfiddle.net/simpulton/q8r4e/.

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>

Single selecting an item on a table

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

Categories

Resources