I am just getting started with Angular and am still trying to get a feel for how it works. I have 2 questions about a list with ng-repeat. I will post my code first.
HTML
<div class="row">
<div class="span2">
<ul class="nav nav-pills nav-stacked">
<li ng-repeat="class in classes | orderBy:orderProp" ng-class="activeClass">
<a ng-click="loadRoster(class)">{{class.class_name}}</a>
</li>
</ul>
</div>
<div class="span2">
<ul class="nav nav-pills nav-stacked">
<li ng-repeat="student in students | orderBy:orderProp">
<a ng-click="enterPassword(student)">{{student.student_name}}</a>
</li>
</ul>
</div>
</div>
Controller
function ClassListCtrl($scope, $http) {
$scope.loadedList=[];
$scope.students=[];
$scope.activeClass='';
$scope.orderProp = 'alphabetical';
$http.get('data/class.json').success(function(data) {
$scope.classes = data;
});
$scope.loadRoster=function(classlist){
$scope.selectedClass=classlist;
$scope.activeClass='active';
if($scope.loadedList[classlist.class_id]== undefined){
$http.get('data/class_'+classlist.class_id+'.json').success(function(data){
$scope.loadedList[classlist.class_id]=data;
$scope.students=data;
});
}
$scope.students=$scope.loadedList[classlist.class_id];
}
$scope.studentClick=function(student){
}
}
Ok, this pulls the data just fine. I can click on a class and it loads the students in that class. To cut down on AJAX calls, I store those that are clicked and if that class is clicked again, it will fetch it from memory instead of making the call. This is fine as class rosters are static for the most part.
I am trying to have it load a default class roster (the first alphabetically) and mark just that list item as active.
Secondly, when they click a list item, I want to change that list item to active, and change the class of the other ones back to nothing. I am not sure how to do that either. As it stands, none are active now, but when I click one, all become active.
in Html ng-class, if class_id matches $scope.activeClass set class of li to "active"
<li ng-repeat="class in classes | orderBy:orderProp" ng-class="{'active':class.class_id == activeClass}">
in Controller when $scope.loadRoster is called set $scope.activeClass to class_id of the class passed to function
$scope.loadRoster=function(classlist){
$scope.selectedClass=classlist;
$scope.activeClass=classlist.class_id;
for your default active class just set $scope.activeClass to class_id of the class
Related
Hello everyone =) I have started to practice Angualar 9 and I really like the component approach. In order to practice property and eventbinding, i started a project of deckbuilding component with two lists. English is not my main language but I will try to explain clearly.
IMPORTANT : I really want to practice this tool, so could you, in the answer, explain your reasoning ? If you have solution tracks, i can search by myself too in order to learn.
GOAL :
I have two lists (CardlistComponent and DecklistComponent) and each time i click on one LI in CardListComponent (or DecklistComponent), this same element is removed but added to the other list.
COMPONENTS :
DeckbuilderComponent which contains my two other components (the two lists)
CardlistComponent (the first list)
DecklistComponent (the second list)
ISSUE :
I can remove the element in CardlistComponent, but I can't add the same element to the DecklistComponent. I guess the problem is the way I use arrays in Javascript.
DeckbuilderComponent (HTML) (Parent component)
<app-cardlist></app-cardlist>
<app-decklist
(cardAdded)="onCardAdded($event)">
</app-decklist>
*DeckbuilderComponent (TS) * (Parent component) I guess one of the problems is here because I duplicated the logic of add an item in the parent AND in DecklistComponent
#Output() cardAdded = new EventEmitter<{name: string}>();
decklist: Card[] = [
new Card('CardC'),
new Card('CardD')
]
onCardAdded(element : HTMLLIElement){
this.decklist.push({
name: element.textContent
})
}
CardlistComponent
#Output() cardRemoved = new EventEmitter<{cardName: string}>();
cardlist: Card[] = [
new Card('CardA'),
new Card('CardB')
]
removeCard(indexCard: number, element: HTMLLIElement){
this.cardlist.splice(indexCard, 1)
this.cardRemoved.emit({
cardName: element.textContent
});
DecklistComponent this list has to recieve the element removed in the first list
#Input() cardName: {name: string};
decklist: Card[] = [
new Card('CardC'),
new Card('CardD')
]
onCardAdded(element : HTMLLIElement){
this.decklist.push({
name: element.textContent
})
}
Here is the HTML of my two components just in case.
DecklistComponent (HTML)
<div class="container">
<div class="col-xs-12">
<ul class="list-group">
<li
*ngFor="let card of decklist; let indexCard=index"
class="list-group-item"
#cardName
>
<a href="#" class="list-group-item list-group-item-action" >{{ card.name }}</a>
</li>
</ul>
</div>
CardlistComponent (HTML)
<div class="container">
<div class="col-xs-12">
<ul class="list-group">
<li *ngFor="let card of cardlist; let indexCard=index" class="list-group-item">
<a href="#"
(click)="removeCard(indexCard, card)"
class="list-group-item list-group-item-action">{{ card.name }}</a>
</li>
</ul>
</div>
If you want something else I didn't mention, don't hesitate to tell me and have a nice day full of code =D
You can design DeckbuilderComponent as Container Component and CardlistComponent, DecklistComponent as Presentational Components
source
Container Components: These components know how to retrieve data from
the service layer. Note that the top-level component of a route is
usually a Container Component, and that is why this type of components
where originally named like that
Presentational Components - these components simply take data as input
and know how to display it on the screen. They also can emit custom
events
<deck-list (remove)="removeAndMoveTo($event, deckList, cardList)" [items]="deckList"></deck-list>
<card-list (remove)="removeAndMoveTo($event, cardList, deckList)" [items]="cardList"></card-list>
<div class="container">
<div class="col-xs-12">
<ul class="list-group">
<li *ngFor="let card of cardlist; let indexCard=index" class="list-group-item">
<a href="#"
(click)="removeCard(card)"
class="list-group-item list-group-item-action">{{ card.name }}</a>
</li>
</ul>
</div>
class CardlistComponent {
#Output("remove") removeCardEmitter: EventEmitter<Card>;
constructor() {
this.removeCardEmitter = new EventEmitter();
}
removeCard(card: Card){
this.removeCardEmitter.emit(card);
};
}
class DeckbuilderComponent {
cardList: Card[];
decklist: Card[];
constructor() {
this.cardList = [
new Card('CardA'),
new Card('CardB')
];
this.decklist = [
new Card('CardC'),
new Card('CardD')
];
}
removeAndMoveTo(card: Card, sourceList: Card[], targetList: Card[]) {
this.sourceList = this.sourceList.filter(pr => pr.id === card.id);
this.targetList.push(card);
}
}
Of course they are many solution to move element from one list to another. You can as well have one list and each card has some information to which group it belongs. Then value input binder would look like [items]="list.filter(pr => pr.isInCardList).
Another single-list approach might use rxjs. One observable which gets split with partition operator
We are creating a tabs widget in ServiceNow and want to initiate the first tab as the active tab when the page loads. Right now when the page loads, this is what we see:
We actually want to see this on load:
Our code looks like this:
<ul class="nav nav-tabs">
<li ng-click="c.activateClass(tabs)" ng-repeat="tabs in c.data.tab_labels track by $index" ng-class="{'active':tabs.active}">
<a data-toggle="tab" href="#{{tabs}}">{{tabs}}</a>
</li>
</ul>
<div class="tab-content" >
<div ng-repeat="content in c.data.tab_labels" id="{{content}}" class="tab-pane fade in active">
<h3>{{content}}</h3>
<p>Some content.</p>
</div>
</div>
function($scope) {
/* widget controller */
var c = this;
c.data.tab_labels = c.options.tab_labels.split(',');
c.activateClass = function(subModule){
subModule.active = !subModule.active;
}
console.log('tabs');
console.log($scope);
}
We tried to use ng-init, but it was returning a console error. Any idea how to initiate the first tab on page load? Thanks!
You can set the active tab as active like this:
if(c.data.tab_labels.length > 0) {
c.data.tab_labels[0].active = true;
}
and show the active content:
<div ng-repeat="content in c.data.tab_labels | filter:{active:true}">
I'm using React version 16.6.3. I need some help to implement active menu item in sidebar. I need to do this thing: when the user clicks on any <li> in sidebar, the <li> must become active (for example, it gets class "active").
If the <li> is active and have treeview class, then, inside it, set to <ul> class "show" (if any)
Here's the code:
import React , { Component } from "react"
export default class Sidebar extends Component {
constructor(props) {
super(props);
this.state = { 'activeItem': 0 }
}
render() {
return (
<div className="main-sidebar">
<section className="sidebar">
<ul className="sidebar-menu tree">
<li className="nav-divider"></li>
<li className="header">PERSONAL</li>
<li>
<a href="#">
<span>Dashboard</span>
</a>
</li>
<li className="treeview">
<a href="#">
<span>Application</span>
</a>
<ul class="treeview-menu">
<li>Chat app</li>
<li>Project</li>
<li>Contact / Employee</li>
</ul>
</li>
<li className="treeview">
<a href="#">
<span>Application</span>
</a>
</li>
</ul>
</section>
</div>
)
}
}
The first question you should ask yourself is (if not always) how you store the data of the user selection. You might have multiple activeItem because this is a tree, ex. multiple branches can be open or close at the same time. You need to look for a data structure to hold that thinking first.
Here's a simple one, give each item an id/key, <li key="1-0-0"> and then you can track onChange event of this li and then inside onChange you can use a flat array structure to store the current state of this simple tree. For example, {'1-0-0': true }
There're lots of different ways to do data part, the above one is a simple idea to get you started. And after that, based on the captured data, you can then update the children attribute of each node, ex. <li className={ getNodeAttr('1-0-0')> assuming getNodeAttr is a utility function that give you back the class name string given the node name.
You should not bind active state on a navigation sidebar because if a user type a route directly in a browser the menu item won't be highlighted.
Instead, try to bind the active state to the route with NavLink (if you use react-router):
ref: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/NavLink.js
My layout page looks like this:
<li class="dropdown">
<ul class="submenu">
<li>#Translate("MY_ACCOUNT")</li>
</ul>
</li>
In layout page i have : #RenderBody()where i have Index page.In index page im using <div ng-view></div>. What im trying to do is when user click on a href to redirect him on that page and set class to this menu that is render in ng-view:
<div class="account-item">
<div class="account-heading" ng-class="{active : activeMenu === 'Settings'}">
<h4 class=" account-title has-sub">
<a data-toggle="collapse" data-parent="#accordion" href="#settings" ng-click="activeMenu='Settings'">5. #Translate("SETTINGS")</a></h4>
</div>
<div id="settings" class="account-collapse collapse in">
<div class="account-body">
#Translate("PERSONAL_INFORMATION")
#Translate("NOTIFICATIONS")
#Translate("CHANGE_PASSWORD")
#Translate("GAME_SETTINGS")
</div>
</div>
</div>
When i try this nothing happens:
$scope.SetActiveMenuForPersonalInfo = function () {
$scope.activeMenu = 'Settings';
$scope.activeLink = "PersonalInfo";
}
$scope.activeMenu and $scope.activeLink are visible only in function and thats why i cant set class on menu. When i put it out of function it works
Try changing the tripple equality sign in ng-class="{'active-link' : activeLink==='PersonalInfo'}" to double ==
PS: I do not understand the last paragraph
ive got a Problem. I want to Show Hide Menuitems when the User ist logged in or logged out.
So i wrote a homecontroller : scope.UserLoggedIn = $window.sessionStorage.getItem('loginToken') != null;
And in my Index.html this :
<div class="collapse navbar-collapse" id="top-navbar">
<ul class="nav navbar-nav">
<li class="pull-left">HOME </li>
<li class="pull-right" data-ng-show="UserLoggedIn">LOGOUT</li>
<li class="pull-right" data-ng-hide="UserLoggedIn">LOGIN</li>
<li class="pull-right" data-ng-hide="UserLoggedIn">REGISTER</li>
</ul>
</div>
The Property is set correct but the Menu disappears only if i refresh the Page. When i logout, i have to Refresh the Page to render the new Menu.
I think, im doing it wrong :/
You have not detailed about your, homeController declaration and when do you set the variable.
But one way to fix this issue would be to use a function instead. Something like
scope.UserLoggedIn = function () {
return $window.sessionStorage.getItem('loginToken') != null;
}
This function would get called every time digest cycle happens so you would always get the correct value.