Set variable while navigating using angular - javascript

Im trying to create a navigation bar but i get stuck with this code.
What happens is when i click the menu it navigates to the right page. When i click again the variable is set. But is it possible to set the variable while navigating.
<div>
<nav class="{{active}}" >
<!-- When a link in the menu is clicked, we set the active variable -->
Home
Projects
Services
</nav>
<p ng-hide="active">Please click a menu item</p>
<p ng-show="active">You chose <b>{{active}}</b></p>
</div>
EDIT
I change the header page to this but i still can get it working.
<div>
<nav ng-controller="testController" class="{{active}}">
<!-- When a link in the menu is clicked, we set the active variable -->
<a href="#/" class="home" >Home</a>
<a href="#/second" class="second" >second</a>
<a href="#/third" class="third" >third</a>
</nav>
</div>
css
nav.home .home,
nav.second .second,
nav.third .third{
background-color:#e35885;
}

You can achieve that by listening to location changes and using the ng-class directive :
CSS :
.active, .active:focus{
color: red;
}
HTML :
<div ng-app="testApp">
<div ng-controller="testController">
<div>
<!-- When a link in the menu is clicked, we set the active variable -->
Home
second
third
</div>
</div>
</div>
Javascript :
var app = angular.module('testApp', []);
app.controller('testController', function ($scope, $location, $rootScope, $log) {
$scope.locationsDescriptions = {
'#/': 'Home',
'#/second': 'Second',
'#/third': 'Third'
}
$scope.isPageSelected = function (pageName) {
return $scope.active == pageName ? 'active' : '';
}
$scope.$on("$locationChangeSuccess", function (event, next, current) {
var location = this.location.hash.toLowerCase();
$scope.active = $scope.locationsDescriptions[location];
});
});

Related

AngularJS : Adding animation when div tag is updated

I am stuck in this problem where I have a div tag which updates and shows a list of images. I want to add animation when the value in the div tag is updated in the transition from one set of images to another.
Here as you can see in the bottom there are a set of images for girl's hair. And when the user goes to other tab, a different set of images comes. I want animation in that transition.
The AngularJS part for the transition is as follows :
<div ng-swipe-left="avDesignController.onSwipeLeftAction()" ng-swipe-right="avDesignController.onSwipeRightAction()">
<!-- CUSTOMIZABLE TAB BAR -->
<div class="tab-bar-container" >
<div class="scrollmenutab">
<!-- CUSTOMIZABLE MENU -->
<div ng-repeat="customizable in customizables"
ng-click="avDesignController.onCustomizableClicked($event)"
style="display: inline;">
<a ng-if="customizable.allowed == 1">
<div ng-class="{selected: $index==currentIndex}">
<div ng-if="customizable.name == 'Hair'">
<img class="scrollmenutab-icon"
id="{{customizable.name}}-{{$index}}"
src="/app/app_resources/icons/{{genderImage}}Hair.png">
</div>
<div ng-if="customizable.name != 'Hair'">
<img class="scrollmenutab-icon"
id="{{customizable.name}}-{{$index}}"
src="/app/app_resources/icons/{{customizable.name}}.png">
</div>
</div>
</a>
</div> <!-- MENU : END -->
</div>
</div>
<!-- CUSTOMIZABLES -->
<div class="avdesign-item-container" id="avdesign-item-container">
<div id="four-columns" class="grid-container" >
<!-- LOAD CUSTOMIZABLES IF NOT LAST ITEM IN TAB -->
<ul ng-if="currentIndex < (customizables.length - 1)"
class="rig columns-4">
<li ng-repeat="customizableItem in currentCustomizable.customizable_item">
<img class="tab-icon"
src="/app/app_resources/resources/av/{{avatarInfo.name}}/as/{{customizableItem.as}}"
id="customizable-{{$index}}"
ng-click="avDesignController.onCustomizedItemClicked($event)"
ng-class="{highlight: customizableItem.id==currentID}">
</li>
</ul>
<!-- LOAD OUTFITS (FROM avatarOutfit) IF LAST ITEM IN TAB -->
<ul ng-if="currentIndex == (customizables.length - 1)"
class="rig columns-outfit">
<div ng-repeat="brand in outfitBrand" ng-style="{'margin-bottom':'1vh'}">
<div class="brand-icon" >
<img src="/app/app_resources/icons/{{brand.bg_image}}">
</div>
<li ng-repeat="outfit in brand.outfitList">
<img class="outfit-icon"
src="/app/app_resources/resources/av/{{avatarInfo.name}}/as/{{outfit.as}}"
id="outfit-{{$index}}"
ng-click="avDesignController.onOutfitItemClicked($event,$parent.$index)"
ng-class="{highlightOutfit: $index==avatar.outfit_index && $parent.$index==indexParent}">
</li>
</div>
</ul>
</div>
</div>
</div>
Where the functions being called in the JS part is updating accordingly the images.
So Question being how to add transition animation for the same element when it is updated because we are never leaving or entering that element tag
Your question is answered here
Html
<div ng-controller="c">
<div id={{my_id}} width={{widthOfOutsideWrapper}} height={{heightOfOutsideWrapper}}>
<img ng-src="{{src}}" imageonload />
</div>
</div>
and in controller
var app = angular.module('app', []);
app.directive('imageonload', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
alert('image is loaded');
scope.widthOfOutsideWrapper= this.width;
scope.heightOfOutsideWrapper= this.height;
scope.my_id = "testing";
});
}
};
});
app.controller('c', function($scope) {
$scope.src ="https://www.google.com.ua/images/srpr/logo4w.png";
});
and http://jsfiddle.net/2CsfZ/855/ working example is available here
The above answer is very helpful and might be of a great help for many.
But the answer to my question is you simply can't. ngAnimate's ngEnter and ngLeave will not able to recognize a change unless the element is changed and not what is inside the element.
So either some hack needs to be applied like using ngRepeat with different id's for different updation that happens to the element or something else needs to be done.

Angularjs nested controller called just one time

I'm new in Angularjs and I have an app, with some "projects", which have a local menu displayed on some pages. Index.html contains the main navbar with footer :
<body ng-app="ysi-app" ng-controller="MainController">
<div class="page-content">
<div class="row">
<div class="col-md-2">
<div class="sidebar content-box" style="display: block;">
<ul class="nav">
<!-- Main menu -->
<li ng-if="isAuthenticated()">{{name}}</li>
<li class="current">Dashboard</li>
<li>Projects</li>
</ul>
</div>
<div ng-if="isAuthenticated() && displayProjectMenu == true" ng-include="'views/localMenu.html'" ng-controller="LocalMenuController">
</div>
</div>
<div ng-view></div>
</div>
So I have a nested controller LocalMenuController for the local menu and a main controller. The project controller sets the datas :
angular.module('ProjectCtrl',[]).controller('ProjectController',function($scope,$location, ProjectService,$route, AuthenticationService, $rootScope){
$scope.setProjectDatas = function(projectName, projectId){
ProjectService.setName(projectName);
$rootScope.projectId = projectId;
};});
I set the id of one project to the $rootScope for testing (I have a Service which will do that better) and get it in the LocalMenuController :
angular.module('LocalMenuCtrl',[]).controller('LocalMenuController', function($scope, ProjectService, $rootScope) {
$scope.projectId = '';
$scope.projectId = $rootScope.projectId;
});
I display projects in a table and when I clicked on one of it, the function setProjectDatas(name,id) is called. The problem is when I clicked on one project, the id of the project is correct and set but when I go previous and clicked on another project, the id is the old id of the project previously clicked. The datas are not updating. I googled my problem but found nothing on it.
I think the LocalMenuController is called only one time but not after.
What am I doing wrong ?
Thank you
UPDATE
I've created a Directive which displays the template but it's still not updating the partial view localMenu.
LocalMenu Directive :
angular.module('LocalMenuCtrl',[]).controller('LocalMenuController', function($scope, ProjectService, $rootScope) {
console.log('-> LocalMenu controller');
})
.directive('localMenu', function($rootScope){
return {
templateUrl: '/YSI-Dev/public/views/partials/localMenu.html',
link: function(scope){
scope.projectId = $rootScope.projectId;
}
};
});
A part of index.html
<div ng-if="isAuthenticated() && displayProjectMenu == true" ng-controller="LocalMenuController">
<div local-menu></div>
</div>
Partial view localMenu :
<div class="sidebar content-box" style="display: block;">
<ul class="nav">
<li><i class="glyphicon glyphicon-list-alt"></i> Backlog</li>
<li><i class="glyphicon glyphicon-user"></i> My team </li>
</ul>
</div>
I'm trying to get the projectId from the $rootScope and inject it in the <a href="#/project/{{projectId}}" but I have some troubles. What's the way to do that ?
First of all, try using directives instead of ng-controller. You can encapsulate your code and template into a unit. You can also try creating a component. Pass some data to the directive/component and Angular will take care of updating the template and running whatever needs to run within the directive/component. (Given that you used two-way data-bindings)
From the code above, I cannot see what would trigger LocalMenuController to run again.

AngularJS - Show div content based on Id clicked

Header Links HTML
<ul ng-controller="pageRouteCtrl">
<li ui-sref-active="active">
<a ui-sref="home" class="" ng-click="getPageId('live-view')">LIVE</a>
</li>
<li>
<a ng-click="getPageId('playback')">PLAYBACK</a>
</li>
</ul>
Ctrl
myApp.controller('pageRouteCtrl', function ($scope, $rootScope) {
$scope.getPageId = function(id) {
$rootScope.route = id;
}
});
Main Page HTML
//should be visible on page load and until playback link is clicked
<div id="live-view" ng-show="route == 'live-view'">
SOME CONTENT
</div>
//will be hidden initially on page load
<div id="playback" ng-show="route == 'playback'">
SOME CONTENT
</div>
The above code works and display <div> content based on link clicked. Subsequently when user clicks on either Live or Playback, div content will be shown.
How do I make live-view div show by default on page load ?
Write following code in controller:
myApp.controller('pageRouteCtrl', function ($scope, $rootScope) {
$rootScope.route = 'live-view';
$scope.getPageId = function(id) {
$rootScope.route = id;
}
});

AngularJS : ng-switch is not triggering when i was clicking second time?

I have a left nav in my one of the view of the application whiich is build using ng-repeat and ng-switch. every link's action associate to a directive in the right hand side. some time, the particular directive will include other directive when user click on the dropdown items from the current directive and page gets extended long and long , so if user want to go to the original state then he can click on the nav item from the left nav to refresh the page to the initial state of the directive. But whenever user clicks on the left nav second time when the left nav already selected, it is not get triggered.I want this get tirggered to bring my initial page of the RHS.
My highlevel code as follows
about.html
<div class="leftNav">
<ul class="nav myNav">
<li class="presentation" ng-repeat="link in links" ng-class="{link-active:currentLink=link.value==param}">
<a ng-href="#/home/{{link.value}}" ng-click="fetchLink(param)">{{link.title}}</a>
</li>
</ul>
</div>
<div ng-switch="fetchLink()">
<div ng-switch-when="About Us">
<div about-us></div>
</div>
<div ng-switch-when="Board Directors">
<div board-directors></div>
</div>
<div ng-switch-when="Our Impacts">
<div our-impacts></div>
</div>
</div>
aboutController.js
$scope.links = [{ title="About Us", value="about"},
{ title="Board Directors",value="board"},
{ title="Our Impacts", value="impact"} ];
var myParam =$root.current.params;
$scope.param = myParam.sec;
//sec has been configured in the route and get
// the values from user's input
$scope.fetchLink() = function() {
var retVal='';
var retVals = $.grep($scope.links, function(item,ind){
return item.value=$scope.param
});
if(retVals.length>0){
retVal = retVals[0].title;
}
return retVal;
};
};
On the router code of app.js
$routeProvider
.when('/about/:sec', {
templateUrl : 'app/view/about.html',
controller: 'aboutController.js'
});
}
When i click the second time, nothing get triggered and fetchLink() method is not triggered.

ng-click not firing $scope.doSomething(), onclick for same function works

The controller I'm using is:
angular.module('app.PostView', [])
.controller('PostViewCtrl', function($scope, $http, Constants) {
$scope.posts = [];
$scope.doSomething = function(){
console.log("in doSomething");
}
$http.get(Constants.POST_URL)
.then(function (response){
console.log(response);
var post = new PostFactory(response.data);
$scope.posts.push(post);
});
})
The view for the controller is
<div ng-repeat="post in posts" >
<div class="home-container">
<div id="details-container">
<!-- using single item Array instead of single iftem to fix linkify bug -->
<div ng-bind="post.desc"></div>
<span class="item-note single-post-details">
<!-- <div class="time-text">{{post.id}}</div> -->
<div class="title" >{{post.title}}</div>
</span>
<a ng-click="doSomething()" href="#" >{{post.name}}</a>
</div>
</div>
</div>
If I replace ng-click with onclick then doSomething is triggered. Currently it is not. The same Controller and html code in other controller/views does work.
When you clicking on the anchor, it change the routing as http://url/#, that listen by the $routeProvider & ng-view loads the default view and template as you are seeing on your side.
Basically you need to remove href="#" from your anchor link or just put href="" blank in that anchor. That would fix your problem.
<a ng-click="doSomething()" href="" >{{post.name}}</a>
Remove href completely
<a ng-click="doSomething()"
style='cursor:pointer' >{{post.name}}</a>

Categories