AngularJS - How to make SPA with multiple sections - angularjs

I have the following basic breakdown of my layout:
<body>
<div id="left"></div>
<div id="content" ng-view></div>
<div id="right"></div>
<body>
I use ng-view in the main content to load the content dynamically through $routeProvider and templateUrl. However, the content in #left and #right also sometime need to change depending on what page I go to.
What's the best way to add/remove elements to #left and #right dynamically? I would basically want that if I load /view1 with controller View1Controller, then if this view has extra components, then I can display them within View1Controller.

In order to do this sort of requirement (without any extra plugins) you'll have to pull your left and right views out into their own view and set each route's main view to include left, content, and right themselves.
Example:
<!-- Core Html-->
<body ng-app>
<div ng-controller="MainCtrl" ng-view></div>
</body>
MainCtrl.js
angular.module('MyApp').controller('MainCtrl', function($scope){
$scope.defaults = {
leftView: "views/view1.html",
rightView: "views/view2.html"
}
});
Route /view1 and it's main view (call it view1.html)
<div ng-controller="View1Ctrl">
<div id="left" ng-include="defaults.leftView"></div>
<div id="content" ng-include="contentView"></div>
<div id="right" ng-include="defaults.rightView></div>
</div>
View1Ctrl
angular.module('MyApp').controller('View1Ctrl', function($scope){
$scope.contentView = "views/view1/firstPanel.html";
//Add some other functions to change $scope.contentView to say
//"views/view1/secondPanel.html"
//You could also temporarily replace $scope.defaults.leftView
//and rightView to show the View1 route in full screen so to speak. like so
$scope.setFullPanel = function(){
$scope.defaults.leftView = ''; //or something else
$scope.defaults.rightView = '';
$scope.contentView = "views/view1/fullScreenPanel.html";
}
});
Route /view2 and it's main view (call it view2.html)
<div ng-controller="View2Ctrl">
<div id="left" ng-include="defaults.leftView"></div>
<div id="content" ng-include="contentView"></div>
<div id="right" ng-include="defaults.rightView></div>
</div>
View2Ctrl
angular.module('MyApp').controller('View2Ctrl', function($scope){
$scope.contentView = "views/view2/firstPanel.html";
//Add some other functions to change $scope.contentView to say
//"views/view2/secondPanel.html"
});
Now that you have the routes and views setup for default left and right panels you could setup a route for a panel with no left and right for example:
<div ng-controller="View3Ctrl">
<div id="content" ng-include="contentView"></div>
</div>
View3Ctrl
angular.module('MyApp').controller('View3Ctrl', function($scope){
$scope.contentView = "views/view3/wholeScreenPanel.html";
});
Hope this helps. Also it's important for "scope hierarchy reasons" to ensure the higher level "default" variables are saved on $scope.defaults so any changes in View1Ctrl or View2Ctrl to $scope.defaults will be properly update throughout all your controllers / views.

I do not completely understand your requirement but did you take a look of the ui-router from angular-ui. Link: http://angular-ui.github.io/ui-router/.
Btw, you can see sample app here: http://angular-ui.github.io/ui-router/sample/#/ Hope it helps.

Related

angularJS: How to conditionnaly display an element outside of ng-view?

Considering the following angular 1.X index.html file:
<div ng-app="app" class="hero-unit">
<a ng-show="!isHomePage" href="#!/home">Home</a>
<div class="container-fluid">
<div ng-view></div>
</div>
</div>
I would like to display the element <a ng-show="!isHomePage" href="#!/home">Home</a> only when the location is not the home page?
How should I proceed? Should I map this element on a dedicated controller as mainController? Is that a good practice?
Ways to achieve this :
You can create a parent level controller(outside ng-view) in the application and then check the current route and based on that implement the condition.
Home
To get the current path you can use :
app.run(function ($rootScope) {
$rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
console.log(current.originalPath); // Do not use $$route here it is private
});
});
OR
$location.path()
You can use $scope.$emit if you want to do it based on any event in the view.$emit will help in communication between child to parent.
You can create an angular service through that you can pass the current state of the application and based on that implement the condition.
Try moving ng-app to the body level, and then use a service in the $rootScope to detect if it's the home page or not - I do this in some of my apps.
e.g.
<body ng-app="app">
<div class="hero-unit">
<a ng-show="!NavigationService.isHomePage()" href="#!/home">Home</a>
<input id="token" type="hidden" value="{{token}}">
<div class="container-fluid">
<div ng-view></div>
</div>
Then in your app.js run method, set the NavigationService to the rootScope,
e.g.
$rootScope.NavigationService = NavigationService;
You can check current url:
See this example from:
https://docs.angularjs.org/api/ngRoute/directive/ngView
<div ng-controller="MainCtrl as main">
<div class="view-animate-container">
<div ng-view class="view-animate"></div>
</div>
<hr />
$location.path() = {{main.$location.path()}}
$route.current.templateUrl = {{main.$route.current.templateUrl}}
$route.current.params = {{main.$route.current.params}}
$routeParams = {{main.$routeParams}}
</div>

Angular two the same controllers in single view

Wondering how to use 2 the same controllers in a single view in Angular, I separated my controllers in different files to make a clean ctrl structure, but wondering if you're allowed to do something like this?
Basically I want to update the table view after uploading a file, its somewhat working but I have to refresh the whole page for the view to refresh.
<div class="view">
<div ng-controller="myCtrl as vm">
controller the table
</div>
<div ng-controller="otherCtrl as vm"> </div>
<div ng-controller="myCtrl as vm">
<button ng-click="clickbtn()"></button>
</div>
</div>
This code is in myCtrl controller.
$scope.$on("$UploadFile", function (event) {
// do the action here digestion
});
$scope.uploadCv = function(event) {
$scope.$broadcast("$UploadFile");
}

How can I show a full screen view with angular's ui-router?

I'm using ui-router and I have the following index view:
<div ng-include="'/views/topbar.html'"></div>
<div class="vm-view">
<div class="container-fluid" ui-view></div>
</div>
So, all the content will be loaded under the top bar. Thats ok, but I need to render a single view without the top bar (full screen). I want to do this without use named views. I want to preserve the index structure intact and states hierarchy too.
Try to add some class depending on current state to hide topbar
<div ng-controller="someCtrl">
<div ng-class="{hide:isSpecialState()}" ng-include="'/views/topbar.html'"></div>
<div class="vm-view">
<div class="container-fluid" ui-view></div>
</div>
</div>
app.controller('someCtrl', function($state) {
$scope.isSpecialState = function() {
return $state.is('<STATE_NAME>');
};
})

AngularJS Trying to use ng-click with ng-switch but ng-switch is not switching my divs

AngNoob here. I have some global navigation that uses the routeProvider to swap out external html pages inside the view. Within the view i set up a list type sub navigation (created with ng-repeat) that switches out divs in the external html file. I can get it to load up the page if I set it manually in the appCtrl:
//Here I set the initial value
$scope.page = 'Comfort Homes of Athens';
But when I click on the span that has the ng-click. I get nothing. I started to think it was a scope issue but when i put just an ng-click='alert()' it does nothing either.
I have read around other posts but most seem to be putting a ng-click inside of an ng-switch rather than the reverse. and aren't using routing in their examples either. Still new to angular so maybe its something I haven't come across yet.
App HTML:
<body ng-app="app">
<header ng-include="header.url" ng-controller="nav"></header>
<article ng-view></article>
<footer ng-include="footer.url" ng-controller="nav"></footer>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-route.js"></script>
<script type="text/javascript" src="js/data.js"></script>
<script type="text/javascript" src="js/model.js"></script>
</body>
External HTML File:
<div id="web" class="wrapper">
<aside class="boxModel">
<div id="controller" class="container">
<div class="topBox bluebg subNavBar"><h1 class="white">Projects</h1></div>
<div ng-controller="nav" id="controls" class="botBox whitebg">
<span ng-repeat='item in webProjects' ng-click="page='{{item.name}}'">{{item.name}}</span>
</div>
</div>
</aside><section ng-switch on="page" class="boxModel">
<div ng-switch-when="Comfort Homes of Athens" id="sandbox" class="container round box whitebg">
<h1>Here is link 1</h1>
</div>
<div ng-switch-when="Sealpak Incorporated" id="sandbox" class="container round box whitebg">
<h1>here is Link 2</h1>
</div>
</section>
</div>
JS:
var app = angular.module("app", ["ngRoute"]);
function nav($scope) {
$scope.templates = templates;
$scope.header = $scope.templates[0];
$scope.footer = $scope.templates[1];
$scope.mainNav = mainNav;
$scope.footNav = footNav;
}
app.config(function($routeProvider) {
$routeProvider.when('/',{
templateUrl: "templates/home.html",
controller: "AppCtrl"
}).when('/templates/web.html',{
templateUrl: "templates/web.html",
controller: "AppCtrl"
}).when('/templates/seo.html',{
templateUrl: "templates/seo.html",
controller: "AppCtrl"
}).otherwise({
template: "This doesn't exist!"
});
});
app.controller("AppCtrl", function($scope) {
$scope.webProjects = webProjects;
$scope.seoProjects = seoProjects;
//Here I set the initial value
$scope.page = 'Comfort Homes of Athens';
});
Unfortunately for you, ng-repeat creates child scopes which are siblings with each other and children of your parent controller (ng-controller="nav") while your <section> where ng-switch is on is not child scope of your ng-controller="nav", but AppCtrl.
You could try ng-click="$parent.$parent.page=item.name" just to understand scopes in angular.
<div id="web" class="wrapper">
<aside class="boxModel">
<div id="controller" class="container">
<div class="topBox bluebg subNavBar"><h1 class="white">Projects</h1></div>
<div ng-controller="nav" id="controls" class="botBox whitebg">
<span ng-repeat='item in webProjects' ng-click="$parent.$parent.page=item.name">{{item.name}}</span>
</div>
</div>
</aside><section ng-switch on="page" class="boxModel">
<div ng-switch-when="Comfort Homes of Athens" id="sandbox" class="container round box whitebg">
<h1>Here is link 1</h1>
</div>
<div ng-switch-when="Sealpak Incorporated" id="sandbox" class="container round box whitebg">
<h1>here is Link 2</h1>
</div>
</section>
I don't recommend using this solution as it's quite ugly. The solution of #link64 is better, but I think the inheritance of model is so implicit and creates a tightly-coupled code. Here I propose another solution which I hope is better by emitting an event:
<span ng-repeat='item in webProjects' ng-click="$emit('pageChange',item.name)">{{item.name}}</span>
I'm not sure if angular is able to resolve $emit('pageChange',item.name) expression in the template. If you run into any problems, you could write inside your controller:
<span ng-repeat='item in webProjects' ng-click="setPageChange(item.name)">{{item.name}}</span>
In your nav controller:
$scope.setPageChange = function (pageName) {
$scope.$emit("pageChange",pageName);
}
In your AppCtrl, listen to the event and update the page.
app.controller("AppCtrl", function($scope) {
$scope.webProjects = webProjects;
$scope.seoProjects = seoProjects;
//Here I set the initial value
$scope.page = 'Comfort Homes of Athens';
$scope.$on("pageChange", function (event, newPage){
$scope.page = newPage;
}
});
In addition to #KhanhTo's answer, I wanted to point you toward another tool to use instead of ngRoute; UI-Router. This is not the answer to your original question, but it is a better solution that avoids your issue entirely.
UI-Router enhances the page routing of ngRoute and is more centered around states. You transition to states that have templates and optional controllers. It emits its own events such as $stateChangeStart or $stateChangeSuccess. You can invoke these state transitions with the function command $state.go(stateName) or by a directive ui-sref="my.state({name: item.name})
UI-Router is a very powerful tool and I cannot go into all the details here but the documentation and community is great.
A simple rewrite of your code could look like the following.
Template for web.html
<div class="wrapper">
<aside class="boxModel">
<div id="controller" class="container">
<div class="topBox bluebg subNavBar"><h1 class="white">Projects</h1></div>
<div ng-controller="nav" id="controls" class="botBox whitebg">
<span ng-repeat='item in webProjects' ui-sref="app.web.page({name: {{item.name}})">
{{item.name}}
</span>
</div>
</div>
</aside>
<section class="boxModel">
<div ui-view class="container round box whitebg">
<!-- Page content will go here -->
</div>
</section>
</div>
JavaScript
app.config(function($stateProvider) {
$stateProvider
.state('app', {
abstract: true,
template: '<div ui-view></div>', //Basic template
controller: "AppCtrl",
}).state('app.home', {
templateUrl: "templates/home.html",
url: '/home'
}).state('app.web',{
templateUrl: "templates/web.html",
url: '/web'
}).state('app.web.page',{
templateUrl: "templates/page.web.html",
url: '/web/page/:name' //Note here the ':' means name will be a parameter in the url
}).state('app.seo',{
templateUrl: "templates/seo.html",
url: '/seo'
});
});
app.controller('AppCtrl', function($scope){
$scope.webProjects = webProjects;
$scope.seoProjects = seoProjects;
$scope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams){
if(newState.name == 'app.web.page'){
var pageName = newStateParams.name; //Variable name matches
$scope.linkText = fetchPageContent(pageName);
}
});
});
Template for page.web.html
<h1>{{linkText}}</h1>
With these changes you will be able to reuse the same instance of your controller. In addition to allowing your paging content to be more scalable.
Notes on $scopes
Every $scope has a parent except for the $rootScope. When you ask for an object in the view, it will look at its $scope to find the reference. If it does not have the reference, it will traverse up to its parent scope and look again. This occurs until you get to the $rootScope.
If you assign something to the $scope in the view, it will assign it to the current $scope as opposed to searching up the $scope chain for an existing property. That is why ng-click="model.page = ..." works; it looks up the $scope chaing for model and then assigns to the page property whereas ng-click="page = ..." assigns directly to the current $scope.
Notes on Controller re-use
To my knowledge, ngRoute does not support nested views. When you go to a new route, it will destroy the current view and controller as specified in the $routeProvider and then instantiate a new controller for the new view. UI-Router supports nested states (i.e. child states with child $scopes). This allows us to create a parent controller that can be re-used amongst all the child states.
I think this may be related to some misunderstanding of how scope works.
ng-repeat creates its own scope. When attempting to set page, angular creates it on the scope of the ng-repeat.
In your AppCtrl, create an object on the scope as follows:
$scope.model = {};
$scope.model.page = 'Comfort Homes of Athens';//Default value
On your ng-click, refer to model.page instead of just page. Angular will then traverse up the scope to find model.page instead of just create a property on the local scope of the ng-repeat.
<span ng-repeat='item in webProjects' ng-click="model.page='{{item.name}}'">{{item.name}}</span>
Also, your AppCtrl is going to be recreated every time you change pages. You should probably use a service to persist the state between page changes

Hide element outside the ng-view DOM based on route

Question:
How can I add a "Login" view/route to my angular app that hides an element that is outside the ng-view DOM?
Situation:
In my Angular page, I have a navigation tree view on the left and the main view in the center:
<div ng-app="myApp">
<div class="col-sm-3" ng-controller="TreeController">
<div treeviewdirective-here>
</div>
</div>
<div class="col-sm-9 content" ng-view="">
</div>
</div>
Each node in the treeview changes the location using something like window.location.hash = '#/' + routeForTheClickedItem;.
Using the standard routing, this works great, i.e. the tree is not reloaded each time, but only the main "window".
Problem:
I want to add a login functionality with a login view. For this view, the treeview should not be visible - only after the login. To achieve this with the normal routing, I know I could move the ng-view one level up, i.e. embed the treeview into each view - but this would result in the treeview being reloaded with every route change.
Is there an easy alternative that allows me to check what page is displayed in the ng-view? Or check some other variable set during the routing? Then I could use something like:
<div class="col-sm-3" ng-controller="TreeController" ng-show="IsUserLoggedIn">
You could listen for a routeChangeSuccess outside ng-view
$scope.$on('$routeChangeSuccess', function (event, currentRoute, previousRoute) {
//do something here
});
hope that helps, you can catch me on angularjs IRC - maurycyg
You could define a controller at the top div level.
Something like:
<div ng-app="myApp" ng-controller="MainController">
and in MainController inject a Session. Something like Session is enough to decide whether to show the tree.
Here's an example of MainController:
_app.controller('MainController', function ($scope, SessionService) {
$scope.user = SessionService.getUser();
});
Here's an example of SessionService:
_app.factory('SessionService', function() {
var user = null;
return {
getUser : function() {
return user;
},
setUser : function(newUser) {
user= newUser;
}
};
});
Of course, when you login you must set the user to the SessionService. Therefore, a SessionService has to be injected into your LoginController, too.
And finally, your html:
<div ng-app="myApp" ng-controller="MainController">
<div class="col-sm-3" ng-controller="TreeController">
<div ng-hide="user == null" treeviewdirective-here>
</div>
</div>
<div class="col-sm-9 content" ng-view="">
</div>
</div>

Resources