AngularJS Show Hide Element only on Page Refresh - angularjs

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.

Related

Angularjs: initiating first tab as active on page load

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}">

ng-click toggle only works on first click

I want to toggle a boolean by click event using Angular.
This is my the code
<div class="nav_mobile" ng-click="mobilestatus.navActive = (mobilestatus.navActive == false) ? true : false">
</div>
<nav>
<ul class="nav_mobile_list" ng-class="{active: mobilestatus.navActive}">
<li><a ui-sref="about" ng-click="mobilestatus.navActive = false">About</a></li>
<li><a ui-sref="contact" ng-click="mobilestatus.navActive = false">Contact</a></li>
</ul>
</nav>
The controller looks like this
angular.module('app').controller('NavCtrl', function ($scope){
$scope.mobilestatus = {navActive: false};
});
I also tried other shorthand notations. The initial value of navActive is false. The ng-click on nav_mobile makes the navActive attribute true the first time, but when clicking again, it doesn't return back to false. When clicking on the li items, the navActive does return back to false. Any suggestion is appreciated.
Try this statement
ng-click="mobilestatus.navActive = !mobilestatus.navActive"
EDIT
If you have no idea of whats going on inside your code try to debug it. Use function call instead of angular's DOM expression and log output into console. Also you can use breakpoints.
HTML
ng-click="toggle()"
Controller
$scope.toggle = function toggle() {
$scope.mobilestatus.navActive = !$scope.mobilestatus.navActive;
console.log('Status is ' + $scope.mobilestatus.navActive);
};
You will see if this code is executable and $scope.mobilestatus is available to html part.
EDIT
Here is plunker
Check this solution:
<div class="nav_mobile" ng-click="mobilestatus.navActive = !mobilestatus.navActive">
Test- {{mobilestatus.navActive}}
</div>
<nav>
<ul ng-class="{'active': mobilestatus.navActive, 'inactive': mobilestatus.navActive}">
<li><a ui-sref="about" ng-click="mobilestatus.navActive = !mobilestatus.navActive">About</a></li>
<li><a ui-sref="contact" ng-click="mobilestatus.navActive = !mobilestatus.navActive">Contact</a></li>
</ul>
</nav>

How to refer DOM elements ID using "a href" inside views - Angular JS

I have tried to find some solution on google about this but couldn't get an exact answer.
I am trying to change tabs inside a view using below code:
<ul class="nav nav-tabs">
<li class="{active: selectedTab === 'details'}"><a href ng-click="selectTab('details')">Details</a></li>
<li class="{active: selectedTab === 'size'}"><a href ng-click="selectTab('size')">Size</a></li>
<li class="{active: selectedTab === 'shipping'}"><a href ng-click="selectTab('shipping')">Shipping</a></li>
</ul>
But whenever I am clicking on "Size" tab, the view redirects to some page. I mean URL changes
from http://localhost:8080/abcd/index.html#/ TO http://localhost:8080/Final_Albatross/index.html#/size
Without view implementation, the click refers to id "size" and tab changes.
Definitely angular is treating this click as a new view call. Please help me out!!
My JS file:
mainAngular.controller('ProductDetailController', function($scope, $routeParams) {
$scope.prod_Id = $routeParams.prodId;
$scope.selectTab = function(tabName) {
alert(tabName);
$scope.selectedTab = tabName;
alert($scope.selectedTab);
}
});
Although I have achieved it using "target="_self" but I want to do it in angular way.
Using anchor links in Angular require target="_self".
https://docs.angularjs.org/guide/$location
<ul>
<li>Link</li>
<li>Anchor</li>
</ul>
Forget about the jQuery, DOM way to handle that kind of problems. Use the angular way.
In AngularJS, the single point of truth is the model. The view (i.e. the HTML) is only a representation of that model, that changes automatically when the model changes.
So, you want a selected tab. Add that to the model:
$scope.selectedTab = 'details';
You want to be able to change which tab is selected. That is as simple as
$scope.selectTab = function(tabName) {
$scope.selectedTab = tabName;
}
And you want the view to be reflect the model values:
<ul class="nav nav-tabs">
<li class="{active: selectedTab === 'details'}"><a href ng-click="selectTab('details'}">Details</a></li>
<li class="{active: selectedTab === 'size'}"><a href ng-click="selectTab('size'}">Size</a></li>
</ul>

Automatically load a view from the controller after a timer in AngularJS

Basically, what I am attempting to do is create a Slideshow. The reason why I am using Angular for this is to get the benifits from templating and hopefully load only one template to the page at a time.
I have my data in a JSON file which the controller gets:
JSON:
{
"prop_title" : "Hyde Lane, Hyde",
"prop_postcode" : "SP2 7AP",
"prop_price" : "",
"prop_image" : "",
"prop_desc" : "",
"template" : "views/prop-thumbs.html",
"info_image" : "",
"duration" : "4000"
},
Controller:
function AppCtrl($scope, $http) {
//GET THE JSON FILE
$http.get('json/pages.json').success(function (data) {
//ASSIGN THE PAGES TO THE SCOPE
$scope.pages = data;
//LOOP THROUGH THE DATA AND ASSIGN THE VIEW
for (var i = $scope.pages.length - 1; i >= 0; i--) {
};
});
}
As you can see from my JSON file, each element contains the view file to use, and the duration that it needs to stay on screen for. Also, as you can see in my controller, I have begun creating a for loop that will hopefully contain my code that will assign view on a timer. Is this possible? Whats the easiest and best way to do this?
Any help seriously appreciated, I have pretty tried everything now!
as Mark Rajcok pointed in the comments, you will probably need to use a $timeout
Here is what I would have done : http://jsfiddle.net/DotDotDot/zbg57/
The html part is quite simple, I just tell angular to include what is in the whatToInclude variable :
<div ng-include='whatToInclude'></div>
On the controller side, I initialize the data with a template and a counter, then I define a nextSlide function, which will call the next template with the timeout passed in parameter. I call this function to start the loop with the initials parameter (0s timeout, first element of the data)
$scope.whatToInclude='tpl1.html';
$scope.count=0;
$scope.nextSlide=function(timeOut){
$timeout(function(){
$scope.whatToInclude=$scope.data[$scope.count].template
$scope.count+=1
if($scope.count>=$scope.data.length)
$scope.count=0
$scope.nextSlide($scope.data[$scope.count].duration)
},timeOut);
};
$scope.nextSlide(0)
I think this can be a good start for a slideshow ;)
Have fun
I made a tutorial with a similar goal in mind:
https://www.youtube.com/watch?v=9COtsDovNpM
Basically store the views in an array of some sort and then based on a variable display that template. Angular will not load the template until ng-show='true' so they won't load all at once but as their clicked or cycled through.
Code example from my tutorial.
Replace ng-switch with whatever works for you.
The common premise is "show this template when that is equal to true".
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li ng-class="{active: main.active.tab == 'info'}">
<a ng-click='main.active.tab = "info"'>Settings</a>
</li>
<li ng-class="{active: main.active.tab == 'categories'}">
<a ng-click='main.active.tab = "categories"'>Categories</a>
</li>
<li ng-class="{active: main.active.tab == 'pages'}">
<a ng-click='main.active.tab = "pages"'>Pages</a>
</li>
<li ng-class="{active: main.active.tab == 'locations'}">
<a ng-click='main.active.tab = "locations"; main.locationgroup = {}'>Locations</a>
</li>
<li ng-class="{active: main.active.tab == 'experts'}">
<a ng-click='main.active.tab = "experts";'>Experts</a>
</li>
<li ng-class="{active: main.active.tab == 'resources'}">
<a ng-click='main.active.tab = "resources"'>Resources</a>
</li>
</ul>
<div class="tab-content">
<div ng-switch='main.active.tab'>
<div
ng-switch-when='info'
ng-include='"/apps/series/views/tabs/info.html"'></div>
<div
ng-switch-when='categories'
ng-include='"/apps/series/views/tabs/categories.html"'></div>
<div
ng-switch-when='pages'
ng-include='"/apps/series/views/tabs/pages.html"'></div>
<div
ng-switch-when='locations'
ng-include='"/apps/series/views/tabs/locations.html"'></div>
<div
ng-switch-when='experts'
ng-include='"/apps/series/views/tabs/experts.html"'></div>
<div
ng-switch-when='resources'
ng-include='"/apps/series/views/tabs/resources.html"'></div>
</div>
</div>
</div>

AngularJS - Change class on list when clicked

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

Resources