Conditional partials in Angular.js - angularjs

Angular novice here. I'm trying to wrap my head around the right way to accomplish a basic template issue.
I have a header, which should read “click here to log in” when the user is not logged in, and “Welcome, Dudefellah” (and associated Settings links and whatnot) when a user is logged in.
I've written a Service that is able to return a JSON bundle including a login state and username, but I don't know what “The Angular Way” to express: “if(auth.loggedin), output partials/header.html; else output partials/header_login.html”.
I’m unclear as to whether this logic would belong in the controller, or some kind of “auth” model, or even in the view (that can't be right, right?). Any assistance would be greatly appreciated.

Within the controller once the login state is fetched create a scope variable headerTemplate and assign the name of the template depending on the login state
function MyCtrl($scope, loginService) {
$scope.auth = loginService.getLoginState();
$scope.headerTemplate = $scope.auth ? 'partials/header.html' : 'partials/header_login.html';
}
In in your markup
<div ng-include src="headerTemplate"></div>

There's a sample angular application called angular-app that does this really well. They have a security service, then a toolbar partial and directive that shows things depending on the state.
https://github.com/angular-app/angular-app/tree/master/client/src/common/security
from angular-app:
src/common/security/login/toolbar.tpl.html:
<ul class="nav pull-right">
<li class="divider-vertical"></li>
<li ng-show="isAuthenticated()">
{{currentUser.firstName}} {{currentUser.lastName}}
</li>
<li ng-show="isAuthenticated()" class="logout">
<form class="navbar-form">
<button class="btn logout" ng-click="logout()">Log out</button>
</form>
</li>
<li ng-hide="isAuthenticated()" class="login">
<form class="navbar-form">
<button class="btn login" ng-click="login()">Log in</button>
</form>
</li>
</ul>
src/common/security/login/toolbar.js:
angular.module('security.login.toolbar', [])
// The loginToolbar directive is a reusable widget that can show login or logout buttons
// and information the current authenticated user
.directive('loginToolbar', ['security', function(security) {
var directive = {
templateUrl: 'security/login/toolbar.tpl.html',
restrict: 'E',
replace: true,
scope: true,
link: function($scope, $element, $attrs, $controller) {
$scope.isAuthenticated = security.isAuthenticated;
$scope.login = security.showLogin;
$scope.logout = security.logout;
$scope.$watch(function() {
return security.currentUser;
}, function(currentUser) {
$scope.currentUser = currentUser;
});
}
};
return directive;
}]);

You could also use ui-router which does wonders for conditional routing and for good infrastructure in general. You'll need to define two states:
myapp.config(function($stateProvider, $urlRouterProvider){
...
// Now set up the states
$stateProvider
.state('login', {
parent: account,
url: "/login",
templateUrl: "partials/header_login.html"
})
.state('auth', {
parent: account,
url: "/authorized",
templateUrl: "partials/header.html"
})
})
when you are back from your query, change state by $state.transitionTo('login') or ('auth') and the router will load the right template for you (and also the URL). in general its much better to use a good router as the basis of your app and not give ad-hoc solutions per each case. you could also read a page (I wrote) about it here

Related

AngularJS $state.go is not redirecting to other page

Below is my controller code,
app.controller('logoutCtrl', ['$scope', '$http','$window','$state',
function ($scope, $http,$window,$state) {
$scope.logout = function() {
console.log('inside logmeout');
delete $window.sessionStorage.token;
$state.go('access.login');
};
}]);
HTML
<li class="last" ng-controller="logoutCtrl">
<a href="" ng-click="logout()">
<i class="material-icons">lock</i> Logout
</a>
</li>
app.router.js
.state('access', {
url: '/access',
template: '<div ui-view class=""></div>'
})
.state('access.login', {
url: '/login',
templateUrl: 'partials/ui-login.html',
controller: 'LoginFormController',
resolve: {
deps: ['uiLoad',
function(uiLoad) {
return uiLoad.load(['scripts/controllers/login.js',
'../bower_components/font-awesome/css/font-awesome.css']);
}
]
}
})
When clicking the logout i am not able to redirect to another state('access.login').
The control is coming inside the logout() and able to print the console message and is deleting the token as well but redirect not happening..
Can i get any help..
In your module definition you need to pass 'ui.router' as a dependency in order to use the Angular-UI-Router in your project:
E.g. angular.module('my_app', ['ionic', 'ui.router'])
It works for me as well.
$state.go('the-state-name-in-quotes')
If your web page is displayed within a view, don't forget to include ui-view in the parent page where you want to display the web page.
<div ui-view>
<!-- Child page will appear here -->
</div>

multistep form and sharing data with angular-ui-router

I am trying to create a multistep form and am having trouble sharing data between views/states. I'm not sure that the way I'm even going about this is accurate as I am new to angular-ui-router. Here are my routes:
.state('tab.newEventCategory', {
url: '/activities/new-event-category',
views: {
'tab-patient': {
templateUrl: 'templates/new-event-category.html',
controller: 'ActivityDashboardCtrl'
}
}
})
.state('tab.newEventSubCategory', {
url: '/activities/new-event-sub-category',
views: {
'tab-patient': {
templateUrl: 'templates/new-event-sub-category.html'
}
}
})
I am trying to use the routes above so that once someone chooses a category, they then go to a page where they choose a subcategory. Here is the new-event-category page:
<div ng-repeat="event_category in event_categories" class="padding">
<a class="button button-block button-positive button-large" ng-click="moveToEventSubCategory(event_category)">
{{event_category}}
</a>
</div>
and here is the controller for the page:
.controller('ActivityDashboardCtrl', function($scope, $stateParams, EventCategory, $state) {
$scope.formData = {};
$scope.event_categories = EventCategory.query();
$scope.moveToEventSubCategory = function(event_category){
$scope.formData.category = event_category;
$state.go('tab.newEventSubCategory');
}
})
My issue is that now I want the newEventSubCategory state to have access to the same formData object so it can add subcategories. There will be more pages to this multistep form after this and I want them to all have access to the same formData variable. How do I do this?
If you want to communicate between controllers/states you best option it what #ronnie mentioned; creating a service or factory.
Have a look at this if you want to work out what services are and how to user them: AngularJS Step-by-Step: Services

AngularJS redirect to view on button click

I'm trying to load a new view when a button is clicked. For some reason it isn't working with one of my paths. It will work with the path /lookup and will go to the lookup page, but when I change the path to /search it does nothing? I'm confused.
Here is my controller:
(function () {
'use strict'
angular
.module('crm.ma')
.controller('navbarCtrl', function ($location) {
var vm = this;
vm.redirect = function () {
$location.url('/search');
}
});
})();
Here is my button
<button class="btn default-btn advancedbtn" ng-click="redirect()">Advanced</button>
And here's part of my route file if that will help at all.
.state('index.topnavbar', {
url: '/topnav',
templateUrl: 'app/components/common/topnavbar.html',
controller: 'navbarCtrl as vm'
})
.state('index.search', {
url: '/search',
templateUrl: 'app/components/common/topnav_advancedmodal.html',
controller: 'AdvancedSearchCtrl as vm',
data: {
pageTitle: 'Advanced Search'
}
})
If any other code is needed please let me know. Thanks.
Do you get any errors in the console? Does your template exist? If Angular can't find your template it won't transition to the route. You can check the network requests and console for errors.
You could try using ui-sref:
<a ui-sref="index.search">Advanced</a>
If you prefer to keep the redirect method, can you add a console.log and do you see that log? If not then your scoping is off.
If so, and you prefer to keep your redirect method rather than use ui-sref (in case you want to check something before redirecting), you can inject $state into your controller and call the method:
$state.go('index.search');
Update to add to follow-up question
To help with your follow-up question of reloading if clicking once you're already there, according to the UI-Router documentation, you can specify the option to reload like this:
<a ui-sref="index.search" ui-sref-opts="{ reload: true }">Advanced</a>
Your call for redirect method are not in the scope. You have to change the redirect() to vm.redirect() in the html.
before:
<button class="btn default-btn advancedbtn" ng-click="redirect()">Advanced</button>
after:
<button class="btn default-btn advancedbtn" ng-click="vm.redirect()">Advanced</button>
This might help you
When you alias controller with some name you need to use aliasName in your view
change you code
<button class="btn default-btn advancedbtn" ng-click="vm.redirect()">Advanced</button>
Refer: https://docs.angularjs.org/api/ng/directive/ngController

AngularJS navigation bar directive with a refresh button

I looked online for a solution but I couldn't find one that suites my needs. Tried this and looked into this with no help.
My case is, I designed a mobile app with AngularJS and the app has a navigation bar. Every page has this navigation bar because of that, I decided to move the code to a directive. The navigation bar has a button inside of it and this button will be used to force a refresh on the app's data (similar to facebook's pull to refresh). The navigation bar is displayed in all pages and whenever the user are, if he click's on the button the app has to execute an update and redirects to a certain page to display the results.
The problem is, since the navigation is inside of a directive and the user can click on any screen how do I manage capturing the click on the button, calling the refresh function and redirecting to a page?
Here is my directive and one of the pages I used it.
myAppDirectives.directive('headerMenu', function() {
return {
restrict: 'A',
templateUrl: 'partials/templates/header-menu.html'
};
});
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item left quarter">
<a class="topcoat-icon-button--quiet" snap-toggle>
<span class="topcoat-icon icon-menu-stack"></span>
</a>
</div>
<div class="topcoat-navigation-bar__item right three-quarters">
<a class="topcoat-icon-button--quiet" href="" > <!-- THIS IS THE REFRESH BUTTON -->
<span class="topcoat-icon icon-refresh"></span>
</a>
</div>
Page example:
<div header-menu></div>
<div> MAIN CONTENT </div>
Thank you!
Update 2: I do appreciate the answers about using ui-router. Since my project is already running and almost ready, structural changes like that are not in question. The accepted answer was the one that solved my problem although the others might fit better other people.
Just put a ngClick on this button:
<a class="topcoat-icon-button--quiet" ng-click="redirect()">
And provide a redirect function on the directive's scope:
myAppDirectives.directive('headerMenu', function() {
return {
scope:{},
restrict: 'A',
templateUrl: 'partials/templates/header-menu.html',
link: function(scope){
scope.redirect = function(){
// redirect to...
}
}
};
});
When I need to do this, I use ui-router, and create a view hierarchy that keeps the navigation bar loaded for every page. That way I can have for example, a navbar.html partial, and a state setup like the following:
$stateProvider
.state('header', url: '', templateUrl: 'header.html', controller: 'HeaderCtrl' })
.state('header.page', url: '/somepage', templateUrl: 'page.html', controller: 'PageCtr' })
.state( ...
I agree with Matt Way, ui-router is great solution for syncing nav bars. Although, for my projects I've been using Multiple Named Views config with ui-router, and your able to get real-time sync between main app interactions and the nav bar, negating the need for "refresh buttons".
In addition, if the user wants to return to the previous page, ui-router will maintain app "state", forms/UX/etc will still be as before.
Have a look at the ui-router wiki https://github.com/angular-ui/ui-router/wiki/Multiple-Named-Views.
Basic demo with header sync http://plnkr.co/edit/kYPGZw?p=preview
Basic multi view config (viewC is Nav):
$stateProvider
.state('state1', {
url: "/",
views: {
"viewA": {
template: "1st Tab, index.viewA"
},
"viewB": {
template: '1st Tab, index.viewB<br><a ui-sref=".list">Show List</a>' +
'<div ui-view="viewB.list"></div>'
},
"viewC": {
template: '1st Tab, index.viewC <div ui-view="viewC.list"></div>'
}
}
})
.state('state1.list', {
url: 'list',
views: {
"viewB.list": {
template: '<h2>Nest list viewB</h2><ul>' +
'<li ng-repeat="thing in tab1things">{{thing}}</li></ul>',
controller: 'Tab1ViewBCtrl',
data: {}
},
"viewC.list": {
template: '1st Tab, list.viewC'
}
}
})

use angular-ui-router with bootstrap $modal to create a multi-step wizard

The FAQ for ui-router has a section about integration with bootstrap $modals, but it doesn't mention anything about abstract views. I have 3 views under a single abstract view, so something like the following.
$stateProvider
.state('setup', {
url: '/setup',
templateUrl: 'initialSetup.html',
controller: 'InitialSetupCtrl',
'abstract': true
})
// markup for the static view is
<div class="wizard">
<div ui-view></div>
</div>
.state('setup.stepOne', {
url: '/stepOne',
controller: 'SetupStepOneCtrl',
onEnter: function($stateParams, $state, $modal) {
$modal.open{
backdrop: 'static',
templateUrl: 'setup.stepOne.html',
controller: 'SetupStepOneCtrl'
})
}
})
.state('setup.stepTwo', {
url: '/stepTwo',
controller: 'SetupStepTwoCtrl',
onEnter: function($stateParams, $state, $modal) {
$modal.open({
backdrop: 'static',
templateUrl: 'setup.stepTwo.html',
controller: 'SetupStepTwoCtrl'
})
}
})
.state('setup.stepThree', {
url: '/stepThree',
templateUrl: 'setup.stepThree.html',
controller: 'SetupStepThreeCtrl'
...
});
}]);
I've also tried to only add the onEnter block to the abstract state, and removed onEnter from each of the 3 child states. This actually seems to me like the right approach. The abstract state initializes and opens the $modal and the subsequent states should interpolate into , but when I tried this the ui-view container was empty.
I can think of some other hacky ways to workaround this but thought I'd ask to see if there's a canonical way of handling this.
Alternative way is to use ng-switch with ng-include combination inside $modal controller to dynamically load wizard step templates, that is if you don't mind sharing the same controller for all wizard steps:
<div ng-switch="currentStep.number">
<div ng-switch-when="1">
<ng-include src="'wizardModalStep1.html'"></ng-include>
</div>
<div ng-switch-when="2">
<ng-include src="'wizardModalStep2.html'"></ng-include>
</div>
<div ng-switch-when="3">
<ng-include src="'wizardModalStep3.html'"></ng-include>
</div>
</div>
Here is Plunker with working example: http://plnkr.co/edit/Og2U2fZSc3VECtPdnhS1?p=preview
Hope that helps someone !!
I used following approach to develop a wizard. this might be help for you.
I used states like below sample with parent property.
var home = {
name: 'home',
url: '/home',
controller: 'MainController',
templateUrl: '/html/main.html'
},
sampleWizard = {
name: 'sampleWizard',
url: '/sampleWizard',
controller: 'sampleWizardController',
templateUrl: '/html/sd/sample/sampleWizard.html'
},
sampleSectionOne = {
name: 'sampleSectionOne',
url: '/sampleSectionOne',
parent: sampleWizard,
controller: 'sampleSectionOneController',
templateUrl: '/html/sd/sample/sampleSectionOne.html'
},
sampleSectionTwo = {
name: 'sampleSectionTwo',
url: '/sampleSectionTwo',
parent: sampleWizard,
controller: 'sampleSectionTwoController',
templateUrl: '/html/sd/sample/sampleSectionTwo.html'
};
$stateProvider.state(home);
$stateProvider.state(sampleWizard);
$stateProvider.state(sampleSectionOne);
$stateProvider.state(sampleSectionTwo);
I'm not sure you want to fire the modal every single time you go to the next step.
I think all you have to do is create a modal view () then each step has a modal a templateUrl assigned to it.
each template should look like:
<div class="modal fade in" id="whatever" style="display:block">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a ui-sref="next_page_route_id" type="button" class="btn btn-primary">Next</a>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div class="modal-backdrop fade in"></div>
On the last screen you can add a data-dismiss="modal" to the submit and you are done
I have dealt with similar scenario, where I had to create a wizard (which allows you to go through steps and finally hit on summary and save).
For this, I had created different views but with one controller.
Since controller scope dies after each re-routing, I had to save the scope of controller(Basically the model object associated with the wizard) in a service object for each routing in the wizard (Captured through location.path()) and load this object back from service object on load of controller.Something like below:-
// Saving data on routing
$scope.nextPage = function () {
service.ModelForWizard = $scope.ModelForWizard;
switch ($location.path()) {
case RouteOfPage1:
//Do some stuff
break;
case RouteOfPage2:
//Do some stuff
break;
default:
}
Service or factory is persisted throughout life time of user session and is ideal to hold user data.
One more thing which was helpful , was use of 'Resolve' in the routes.
It ensures that next page in not rendered until the required data(generally lookup data) is not loaded. Code of resolve is something like this:
.when('/RouteForWizardPage1', {
templateUrl: '/templates/ViewPage1Wizard.html',
caseInsensitiveMatch: true,
controller: 'wizardController',
resolve: {
wizardLookupDataPage1: function (Service) {
return service.getwizardModelLookupDataPage1().$promise;
}
},
})
I was running into the same thing.. What worked for me was emptying the url property of the first sub state. Hence for the first sub state, your code should look as follows:
.state('setup.stepOne', {
url: '',
controller: 'SetupStepOneCtrl',
onEnter: function($stateParams, $state, $modal) {
$modal.open{
backdrop: 'static',
templateUrl: 'setup.stepOne.html',
controller: 'SetupStepOneCtrl'
})
}
})
Also, incase you're not using the url property to call the other 3 sub states, and are calling them using the state name only, you don't necessarily need to mention a url property for them.
If you want to show a wizard in a modal dialog and have a separate state for each of the wizard's steps, you need to keep in mind that the modal dialog is rendered completely outside your view hierarchy. Therefore, you cannot expect any interaction between ui-router's view rendering mechanisms and the dialog contents.
A robust solution is to put the wizard contents manipulation logic onto the parent state scope
$scope.wizard = {
scope: $scope.$new(),
show: function (template) {
// open the $modal if not open yet
// purge scope using angular.copy()
// return $scope.wizard.scope
},
// private
open: function () {
$modal.open({
scope: $scope.wizard.scope,
// ...
});
}
};
and then manually show the appropriate content from each of the sub-states and manipulate the wizard's scope as needed
$scope.wizard.show('someTemplate');
$scope.wizard.scope.user = ...;
When we faced this problem in our project, we decided after some discussion, that we didn't actually need separate ui-router states for the wizard steps. This allowed us to create a wizard directive used inside the dialog template to read wizard configuration from scope (using a format similar to ui-router state definition), provide methods to advance the wizard, and render appropriate view/controller inside the dialog.
To create multi-step wizards, you can use this module (I am the author): https://github.com/troch/angular-multi-step-form.
It allows you to create steps like views, and you can enable navigation (back / forward button, url with an URL search parameter). Examples are available here.

Resources