ng-click toggle only works on first click - angularjs

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>

Related

How to implement the Bootstrap pills active class with Angular

I want to create a set of pills with all the states with their number of electors and I want the pill that is clicked becomes active. So, my unsuccesful attempt for this matter is as follows:
<ul class="nav nav-pills">
<li ng-class="{ active:tab.isSet(x.name) }" ng-repeat="x in states">
<a href ng-click="tab.setTab(x.name)">{{x.name}} <span class="badge">{{x.elector}}</span></a>
</li>
</ul>
And, inside my controller I have this piece of code for that matter:
$scope.tab = "Alabama";
$scope.isSet = function(checkTab) {
return $scope.tab === checkTab;
};
$scope.setTab = function(activeTab) {
$scope.tab = activeTab;
};
By the way, at first I tried to make the pills active by comparing their indices but that didn't help. It would be even better if you can help me with a way to do this using the indices. I apologize if there is already a posted solution to this but I couldn't find it.
Thanks in advance!
<ul class="nav nav-pills">
<li ng-class="{ 'active':tab.isSet(x.name) }" ng-repeat="x in states">
<a href ng-click="tab.setTab(x.name)">{{x.name}} <span class="badge">{{x.elector}}</span></a>
</li>
</ul>
Note the quotes around active
I found it, I should've deleted the "tab"s in "tab.isset(...)".

$scope is only visible in function and thats why is not working

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

How to set bootstrap active tab on refresh in Angular JS

I am creating tabs as:
<tabset class="content-tabset no-margin">
<tab ng-repeat="t in t.values" heading="{{t.name}}" active="t.active">
//other stuff
</tab>
</tabset>
Now within this other stuff I also have button which when clicks updates the row and refreshes that part. When the refresh happens it also resets the tab I am currently on.
So if I am tab two and click on the button, the panel refreshes and I come back on tab 1. How can I prevent this?
Use localStorage. Set it on selecting tab. To get boolean value of active state for current tab use ng-init.
<tabset class="content-tabset no-margin">
<tab
ng-repeat="t in t.values"
heading="{{t.name}}"
ng-init="isActive = isActiveTab(t.name, $index)"
active="isActive"
select="setActiveTab(t.name)">
//other stuff
</tab>
</tabset>
And in your controller
$scope.setActiveTab = function( activeTab ){
localStorage.setItem("activeTab", activeTab);
};
$scope.getActiveTab = function(){
return localStorage.getItem("activeTab");
};
$scope.isActiveTab = function( tabName, index ){
var activeTab = $scope.getActiveTab();
return ( activeTab === tabName || ( activeTab === null && $index === 0 ) );
};
NOTE: Since your t has no unique ID for tabs, names should be unique to detect active tab correctly.
See example JSFiddle.
Whenever you do a refresh the local/scope variables runs out of scope. So the way out to solve this is using JavaScript's Session Storage/ Local Storage.
Session storage will run out of scope once you close the browser while local storage will persist value till window and browser lifetimes.
Inside controller:
$scope.selTab = sessionStorage.tabName; //On refresh it will fetch value from session storage
$scope.onClickTab = function(tabName){ //On click it will set the sessionStorage
$scope.selTab = tabName;
sessionStorage.tabName = tabName;
}
Inside HTML must refer your controller
<ul class="nav nav-pills col-md-12 col-sm-12 col-xs-12{{active}}">
<li ng-class ="{active:selTab=='tab1'}">Tab3</li>
<li ng-class ="{active:selTab=='tab3'}">Tab3</li>
</ul>
You can use this package ui-router-tabs. Follow the link https://github.com/rpocklin/ui-router-tabs. Easy to use and gets the job done.
I have solved it by using Local Storage
Inside HTML:
<ul class="nav">
<li>
<a ng-click="goToManageUsers('manageUser')" ng-class="{'active': selectedTab == 'manageUser'}">
<i class="lnr lnr-home"></i>
<span>Manage User</span>
</a>
</li>
<li>
<a ng-click="goToManageRequest('manageImage')" ng-class="{'active': selectedTab == 'manageImage'}">
<i class="lnr lnr-home"></i>
<span>Manage Image</span>
</a>
</li>
</ul>
Inside Controller:
$scope.selectedTab = localStorage.getItem('getActive');
$scope.goToManageUsers = function (user) {
$scope.selectedTab = user;
localStorage.setItem('getActive', user);
}
$scope.goToManageRequest = function (image) {
$scope.selectedTab = image;
localStorage.setItem('getActive', image);
}
To do this same thing in Angular 2+, you also use LocalStorage. Something like this (I used ng-bootstrap to enable Bootstrap tabs):
HTML:
<ngb-tabset class="nav-fill" (tabChange)="tabChange($event)" [activeId]="activeTabId">
<ngb-tab title="Tab 1" id="tab1">
...
</ngb-tab>
<ngb-tab title="Tab 2" id="tab2">
...
</ngb-tab>
</ngb-tabset>
.ts:
import {NgbTabChangeEvent} from "#ng-bootstrap/ng-bootstrap";
... other imports
export class MyComponent {
activeTabId: string;
constructor() {
this.activeTabId = localStorage.getItem("activeTab");
}
tabChange($event: NgbTabChangeEvent) {
localStorage.setItem("activeTab", $event.nextId);
}
}

AngularJS Show Hide Element only on Page Refresh

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.

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>

Resources