Angular Js Animate function in custom directive - javascript

Here is the application code:
(function(){
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'home.html'
})
.when('/about', {
templateUrl: 'about.html'
})
.when('/contact', {
templateUrl: 'contact.html'
})
.otherwise({
templateUrl: 'home.html'
})
})
myApp.directive('menuRight', function(){
return {
restrict: 'E',
replace: true,
templateUrl: 'menu.html',
link: function(scope, elem, attrs) {
var mB = document.getElementsByClassName('menuBtn');
var m = document.getElementsByClassName('menu');
var menu = angular.element(m);
var menuButton = angular.element(mB);
menu.css({
"left": -100 + "px"
});
menuButton.click(function(){
if(menu.hasClass('visible')) {
menu.animate({'left': -100 + 'px'}, 200).removeClass('visible');
} else {
menu.animate({'left': 0}, 400).addClass('visible');
}
});
}
}
})
})()
The index file has three tags:
<div ng-view></div>
<button class="menuBtn">Toggle Menu</button><br><br>
<menu-right></menu-right>
This code is working fine.
Running Plunker link:
http://plnkr.co/edit/Q7VO0RZstMBwQzH613an?p=preview
This code is doing two things.
1. Loading a custom directive which is displaying the menu.
2. Routing to 3 pages home, about, contact through that directive.
Now above the custom directive there is a Toggle button that is sliding the menu from left. That is done through link function using jquery.
This directive is using jquery to do slide effect.
Now my Question is:
I would like to improve this code. Using angular Animate.
Or using controller in directive.
There is an active class applied to first li inside the menu template. But when I click on other li tags from menu I need to change the active class from/to the clicked li.
Looking for some great answers from great community.
Thanks...

Related

How have in AngularJS with UI Router, multiple and nested views?

I have been reading about nested views and multiple views but I can't find an example using both
In a landing page I have multiple views, one after other. A picture speaks a thousand words:
To consider:
Every section/view will have full window height, so on scroll I want to change location to /view1, /view2, /view3, etc.
That should be compatible with going to /view1/b or /view3/b and showing subview (view1.b or view3.b).
Scroll should not make load page again.
I have success doing tasks separately but not all together.
you can use $statePorivder nested view with
config(function ($stateProvider) {
$stateProvider
.state('main', {
url: '/',
views: {
'': {
templateUrl: 'app/main/layout.html',
controller: 'LayoutController'
},
'header#main': {
templateUrl: 'app/main/header/layout.html',
controller: require("./headerController.js")
},
'left#main': {
templateUrl: 'app/main/left/layout.html',
controller: require("./leftController.js")
},
'content#main': {
templateUrl: 'app/main/content/layout.html',
controller: require("./conentController.js")
},
'right#main': {
templateUrl: 'app/main/right/layout.html',
controller: require("./rightController.js")
}
}
});
};

Animation in AngularJS Directive, event not firing

I'm trying to do something after an 'enter' event in a directive. The event isn't firing when the template is loaded in.
Here is the app declaration
angular
.module('MyApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
})
.when('/in-the-community', {
templateUrl: 'views/in-the-community.html',
controller: 'CommunityCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Initially I am using the routing provider to give me a template page. I am then trying to use a directive inside these templates to provide another view. This works by using the following in my template page
<div class="flex">
<div class="fc fci image-wrapper" id="home-banner">
</div>
<div class="fc fcc">
<section show-and-hide-content="{{ sub_content }}">
</section>
</div>
</div>
This loads in the following directive
angular.module('rubisApp')
.directive('showAndHideContent', function ($animate) {
return {
templateUrl: 'views/community-sub.html',
controller: 'CommunitySubCtrl',
link: function(scope, element, attributes) {
$animate.on('enter', element,
function callback(element, phase) {
console.log('attributes.showAndHideContent');
}
);
}
};
});
The console log isn't running and I can only presume that is because it isn't firing the $animate.on event.
Does angular apply the ng-enter class to a templateUrl in a directive?
I'm pretty new to angular so if this is the wrong way of doing this, an alternative would really help also.
The $animate dependency as not being pulled into the directive.
angular.module('MyApp')
.directive('showAndHideContent',['$animate', function ($animate) {
return {
templateUrl: 'views/community-sub.html',
controller: 'CommunitySubCtrl',
link: function(scope, element, attributes) {
$animate.on('enter', element,
function callback(element, phase) {
console.log('attributes.showAndHideContent');
}
);
}
};
}]);
i see you are using an controller. can't you create the event there?
I checked my code and have this snippet on controller, to destroy an interval when route changes, notice that i use $on and '$destroy', with $. can it be that?
$scope.$on('$destroy', function () {
$interval.cancel($scope.interval);
});

Bootstrap Carousel not working with angular ng-route

Am creating a simple angularjs application with ng-route, the index.html page have a bootstrap carousel which have next and previous button when click on that button am being navigated to the next Html page below is my plunkr link as well as my script.js file please do corrections if am wrong, I have searched a lot but didn't find a proper solutions for this issue
Working Link
var appname = angular.module('appname', ['ngRoute', 'ngAnimate']);
appname.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'indexView.html',
controller: 'indexController'
}).
when('/about', {
templateUrl: 'about.html',
}).
when('/contact', {
templateUrl: 'contact.html',
}).
otherwise({
redirectTo: '/'
});
}]).controller('MainCtrl', function($scope, $location) {
$scope.isIndexPage = function() {
return $location.path() === '/';
}
});
Check this, everything works nicely now.
http://plnkr.co/edit/JcInw9ZUz6vfFO5InV7N?p=preview
Rewrote the MainCtrl part, before the MainCtrl was created once and never updated, but now it listens to route change and hides the carousel accordingly.
$scope.$on('$routeChangeSuccess', function () {
$scope.isIndexPage = $location.path() === '/';
});

Angularjs - multiple directives nested on the same page

I just started working with AngularJs and am having some problems in the management of multiple directives.
The two directives have to perform the following tasks:
1) Create an animation when the page is loaded with animated
2) Create a background parallax on some div
Through some resources found on the net I could get aa two directives that individually work well, but if I try to make them work together with the outer one prevents the internal directives to do their jobs.
This is the code(html):
<div ng-view ng-controller="MyCtrl" anim-class>
<section parallax-background parallax-ratio="0.5" style="background: url(img/parallax1.jpg);">
//some code
</section>
</div>
This is the code(js):
var app = angular.module("myApp", [
"ngRoute",
"ngAnimate",
]);
app.config(function($routeProvider, $locationProvider) {
$routeProvider.
when("/first-page", {
templateUrl: "first-page.html",
animate: "slideTop"
}).
when("/second-page", {
templateUrl: "second-page.html",
animate: "slideTop"
}).
otherwise({
redirectTo: "/first-page"
});
});
app.controller("MyCtrl", function($scope) {
});
// PAGE ANIMATE DIRECTIVE
app.directive('animClass',function($route){
return {
link: function(scope, elm, attrs){
var enterClass = $route.current.animate;
elm.addClass(enterClass)
scope.$on('$destroy',function(){
elm.removeClass(enterClass)
elm.addClass($route.current.animate)
})
}
}
});
// PARALLAX DIRECTIVE
app.directive('parallaxBackground', ['$window', function($window) {
return {
restrict: 'A',
transclude: true,
template: '<div ng-transclude></div>',
scope: {
parallaxRatio: '#',
},
link: function($scope, elem, attrs) {
var setPosition = function () {
var calcValY = (elem.prop('offsetTop') - $window.pageYOffset) * ($scope.parallaxRatio ? $scope.parallaxRatio : 1.1 );
// horizontal positioning
elem.css('background-position', "50% " + calcValY + "px");
};
// set our initial position - fixes webkit background render bug
angular.element($window).bind('load', function(e) {
setPosition();
$scope.$apply();
});
angular.element($window).bind("scroll", setPosition);
angular.element($window).bind("touchmove", setPosition);
} // link function
};
}]);
How can I make sure that the two ( or more ) directives are working properly .
Thank You.

AngularJS dynamically set class on <html> tag based on route

I'm not sure the best way to approach this.
I want to dynamically set a class on my /login route so that my login page can have a large background image.
What is the best way to approach this?
Here's my current code:
<!DOCTYPE html>
<html class="SOME_DYNAMIC_CLASS_HERE_BASED_ON_ROUTE">
...
</html>
<body ng-app="myApp">
<div ng-view=""></div>
</body>
angular.module('myApp', ['ngRoute']).config(function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginCtrl'
})
.when('/', {
templateUrl: 'dashboard.html',
controller: 'DashboardCtrl'
})
You must have your ng-app attached in the <html> element, to have any sort of connection between angular and the view. Since you want something to change base on the current route of your application, then why not use those routes as a reference for your configuration, e.g. the $routeProvider configuration. Attach all your configuration, including configuration from classes to styles or any other configuration within the route object. You can then create a directive that listens to route changes via $routeChangeSuccess and then get the current route and other properties using the $route object defined as the second parameter of the $routeChangeSuccess listener, once you have those properties, you can do whatever you want with it e.g. append a class to that directive element.
DEMO
Javascript
Configuration
.config(function ($routeProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: 'dashboard.html',
'class': 'bg-dashboard'
})
.when('/login', {
templateUrl: 'login.html',
'class': 'bg-login'
})
.otherwise({redirectTo: '/login'});
});
Directive
.directive('classRoute', function($rootScope, $route) {
return function(scope, elem, attr) {
var previous = '';
$rootScope.$on('$routeChangeSuccess', function(event, currentRoute) {
var route = currentRoute.$$route;
if(route) {
var cls = route['class'];
if(previous) {
attr.$removeClass(previous);
}
if(cls) {
previous = cls;
attr.$addClass(cls);
}
}
});
};
});
HTML
<html ng-app="myApp" class-route>...</html>
Using a directive is one way to go.
.directive("routeClass", function($location, $parse) {
var mapping = {};
return {
restrict: "A",
scope: {},
link: function(scope, element, attrs) {
mapping = $parse(attrs["routeClass"])(scope);
// do something with mapping and $location or $routeParams
}
}
});
<any route-class="{'/': 'default', '/Book': 'book'}" />
Another - is to set it via $rootScope.
I know this is an old thread, but I came across it looking for some pointers. I have gone for the following method which feels more "Angular". Note, it is using a controllerAs-based directive:
ngModule.directive('routeClass', routeClass);
function routeClass($state, $log) {
function controllerFn($scope) {
var routeClass = this;
$scope.$on('$stateChangeSuccess', function(){
// I have a different class name assignment as the
// setup of my states is relatively complex,
// but this should demonstrate the idea
routeClass.current = 'page-' + $state.current.name;
});
}
return {
controller: controllerFn,
controllerAs: 'routeClass',
restrict: 'A'
};
}
And it is used as follows in index.html:
<body ng-app="app" route-class ng-class="{{routeClass.current}}">

Categories

Resources