AngularJS handling data outside ng-view - angularjs

Inside my AngularJS app index.html page I have three main divs (top, footer and ) which display different views depending on current route. The problem I am facing now is that I need to display some data in the footer area, including data that will require loop (ex. list of States, Cities...etc) but I am not sure how to display data in index.html outside of the ng-view. So can someone tell me how this can be accomplished? Any example code is highly appreciated. Thanks
Below is my index.html structure, App.js
app.js
var myApp = angular.module('myApp', ['ngRoute', 'ngSanitize']);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/',
{ templateUrl: 'templates/home.html',
controller: 'HController',
title: 'Home',
});
}]);
Index.html
<html lang="en" ng-app="myApp">
<head>...</head>
<div id="header">....</div>
<div ng-view></div>
<div id="header">
<!-- Here is where I need to loop to display data -->
</div>

Using ngRoute and ng-view does not preclude using ng-controller and other angular constructs in your code as long as the code resides inside an element which has ng-app attribute (or has been bootstrapped).
So, since you have ng-app attribute on html, you can define a new controller and use it in #header:
index.html:
<div id="header" ng-controller="headerController">
{{myData}}
<!-- Here is where I need to loop to display data -->
</div>
app.js:
myApp.controller('headerController',
[ '$scope', function ($scope) {
$scope.myData = 'Stuff.';
}]
);

Related

related to angularJS routing why routing not working properly

I am trying to create a single page application demo for practice.I have stored all three html files in same folder. I tried to give whole path of pages.I tried giving container ng-view /ng-view. I am using brackets editor for this. Change in url can be seen but it is not displaying contents from html pages Login.html and About.html in container ng-view.Please help.. my code is here:
<!DOCTYPE html><html><head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route/angular-route.min.js"></script>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider)
{
$routeProvider
.when("/", {
templateUrl : "/Index.html"
})
.when("/red", {
templateUrl : "/Login.html"
})
.when("/green", {
templateUrl : "/About.html"
});
});
</script>
</head>
<body ng-app="myApp">
<ul>
<li>Main</li>
<li>Red</li>
<li>Green</li>
</ul>
<p>Click on the links.</p>
<p>This example uses the ng-view directive as an attribute to a DIV element.</p>
<div ng-view> </div>
</body>
Probably a problem with the relative paths that was supplied to "templateUrl".
Try to change to "template" and just add a simple Test - page name
element for each page.
If you can see all the pages - that means that the problem is in the relative paths you proved to templateUrl.
and maybe try to put the "/" route at the end (i don't remember in angular 1.x but in angular 2+ the order matter).

angular - Switch navbar when view is changed

I am using angular-route.min.js and I have two designs for my navbar.
The First one is the landing page navbar that will appear first on my index.html.
The second navbar is when the user is routed to the /signin page.
I am unsure on how to go about this. I see a lot of different ways that this could be done, but none really that explain how I could change the entire header view when another route is chosen. They just show how to change the links that are contained inside of it. Like this Stack
how can I switch out the header when it is routed to the /signin page?
also, I am working with another person who is doing the backend with Django. That is why I changed the "{{ }}" to "[[ ]]".
var app = angular.module('app', ['ui.bootstrap', 'ngRoute']);
app.config(function($interpolateProvider, $routeProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
$routeProvider
.when('/', {
templateUrl: 'pages/LandingPage.html',
})
.when('/signin', {
templateUrl: 'pages/SignIn.html'
})
.when('/contact', {
templateUrl: 'pages/contact.html'
});
});
<!DOCTYPE html>
<html lang="en" data-ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js">
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-route.js">
</script>
</head>
<body>
<div ng-view></div>
</body>
</html>
I think ng-include directive could solve the situation you are facing.
In controller code.
.controller('HeaderCtrl', function($scope, $location) {
$scope.$on('$locationChangeSuccess', function(/* EDIT: remove params for jshint */) {
var path = $location.path();
//EDIT: cope with other path
$scope.templateUrl = (path==='/signin' || path==='/contact') ? 'template/header4signin.html' : 'template/header4normal.html' ;
});
})
In Html.
<body>
<div ng-controller="HeaderCtrl">
<div ng-include="templateUrl"></div>
</div>
<div ng-view></div>
</body>
I hope this could help you. :)
The difference of your two navbars are not significant. An alternative is just use ng-class and ng-show to give different styles.
For example, in the navbar.html:
<nav>
<span ng-show="isNormalPage">Inn</span>
<img ng-class="{align-center: isNormalPage}">Logo</img>
<span ng-show="isNormalPage">Sing in</span>
</nav>
In your JS file, add a flag to mark singin page:
.when('/signin', {
controller: [$scope, function ($scope) {
$scope.isNormalPage = false;
};
}]
})

angularjs single page share the same DIV element

I try to implement a single page app with angularjs
There is the route code:
angular.module('todomvc', ['ngRoute'])
.config(function ($routeProvider) {
'use strict';
$routeProvider.when('/account', {
controller: 'TodoCtrl',
templateUrl: 'account.html'
}).when('/', {
controller: 'TodoCtrl',
templateUrl: 'todomvc-index.html'
}).otherwise({
redirectTo: '/'
});
});
The html of the single page is:
<!doctype html>
<html lang="en" data-framework="angularjs">
<head>
<link rel="stylesheet" ... >
<script ...></script>
</head>
<body ng-app="todomvc">
<ng-view />
<script type="text/ng-template" id="account.html">
a html template segment(*) here
///////////// this is the template of the first appearance. //////////////
</script>
<script type="text/ng-template" id="todomvc-index.html">
the same html template segment(*) here
///////////// this is the template of the second appearance. //////////////
But both appearance share a common template segment. How to remove the duplication?
</script>
</body>
</html>
By default, the second page is show up. After a user click a button on the second page, it will trigger $location.path("account"); and route to jump to the first page. In my case, both templates share a div block, that is, a common part is load to both templates. Currently, the template segment is copy and paste to both areas as shown in above code. But the copy-paste is hard to maintain. How can I share the template segment between the two text/ng-template?
Thank you.
Define your common div in a seperate .html file and include it using the ngInclude directive.
<ng-include src="commonDiv.html"/>
I strongly recommend a module called ui-route which provide a simple and easy way to maintain nested views and templates.

Use ng-controller and $routeProvider at the same time

The issue is that I have an index page, whith a(some) partial(s) view(s) that we can call "A.html" with a controller "ACtrl" assigned by $routeProvider, but inside that partial view, I would like to use a different controller for some divs using ng-controller to include a "A1Ctrl".
Is this possible?
Not focus on any code, but in the concept if this is barely possible and how?
I tried to include in the partial view something like this with no success:
A.html
... //Other stuff for this partial view
<div ng-controller="A1Ctrl">
{{message}}
</div>
... //More stuff for this partial view
I have included the .js where the A1Ctrl is defined to the index page with same result. Any tip?
UPDATE:
I have create in plnkr a sample code to show what I want to do: http://plnkr.co/edit/hdpLMK3DbzNdz2KeHPEB?p=preview
I have partial view generated after clicking "Say hi" which has its own template ("first.html") and controller, injected by the $routeProvider. But in that partial view in first.html I want to add a which has its own controller for only that section of code. But I can't make it work, any suggestion?
I also tried to use Dependency Injection to include the module "multilinguage" into router.js with no success because it seems to generate an error.
index.html
<html ng-app="plunker">
<head>
... //Other imports
<script src="app.js"></script>
<script src="router.js"></script>
<script src="multilanguage.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
Say hi |
Say bye
<br/>
<div ng-view=""></div>
</body>
</html>
first.html
{{message}}
<div ng-controller="MultiLang">
{{message}}
</div>
router.js
var app = angular.module('router', ['ngRoute', 'multilanguage']).
config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when("/first", {
templateUrl: "first.html",
controller: "EngLang"
}).
when("/second", {
template: "Bye man!"
});
});
app.controller('EngLang', function($scope) {
$scope.message = 'Hi guys';
});
multilanguage.js
angular.module('multilanguage', []).
controller('MultiLang', function($scope){
$scope.message = "Hallo, Hola, Ciao, Ni Hao"
});
Thanks in advance.
Yes, also you can use nested controllers, for example:
<div ng-controller="A1Ctrl">
{{ message }}
<div ng-controller="subCtrl">
{{ message }}
</div>
</div>

need advice on ng-view layout please

I am designing a page in angularjs that would be a mini SPA (single page app). This page is part of a larger web site that was written in traditional jquery and asp.net. The page will have 2 main sections - the 1st section is just some simple data elements that can be bound easily with ng-model's. The 2nd section will be dynamically generated based on user's interaction, and the data will be retrieved through ajax ($http or $resource).
So should I have ng-view on the whole content page that contains the 2 sections? Or should I only do ng-view on the 2nd dynamic sections? If it's better to have ng-view on the 2nd section only, how do I handle the routes in this case knowing that the 1st section's data should be preserved statically?
thanks.
You don't have to use ng-view and routes for your simple case (widget-like angular application inside other application). You can use ng-include instead. Here is an example of application. I prefer this approach because it does not require to use shared resource like URL location hash that may be already in a use by legacy application or other widgets. Application below switch views dynamically, loads different data for each view and affects it's display options (number of displayed items):
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="angular.js#*" data-semver="1.2.11" src="http://code.angularjs.org/1.2.11/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Here is my legacy app markup</h1>
<div ng-app="app" ng-controller="appController">
<div>
<input placeholder="Number of items" ng-model="numberOfItems"/><br/>
<select placeholder="View" ng-model="currentView" ng-options="view.name for view in views"></select>
</div>
<div ng-include="currentView.url"></div>
</div>
<div id="jqueryContainer">And here is some markup generated with jQuery<br /></div>
</body>
</html>
JavaScript
angular.module('app', []).
controller('appController', function($scope, $http) {
$scope.views = [{
name: 'view1',
url: 'view1.html',
dataUrl: 'data1.json'
}, {
name: 'view2',
url: 'view2.html',
dataUrl: 'data2.json'
}];
$scope.numberOfItems = 2;
$scope.currentView = $scope.views[0];
$scope.$watch('currentView', function(currentView) {
if(currentView && currentView.dataUrl) {
$http.get(currentView.dataUrl).success(function(data) {
$scope.data = data;
});
}
});
});
$(function(){
$('#jqueryContainer').append('<span>Some markup generated dynamically.</span>');
});
view1.html
<div>
<h2>View1 specific markup {{data.length}}</h2>
<ul>
<li ng-repeat="item in data | limitTo:numberOfItems">{{item.text}}</li>
</ul>
</div>
data1.json
[{"text":"Text1"},{"text":"Text2"},{"text":"Text3"},{"text":"Text4"},{"text":"Text5"}]
Plunker: http://plnkr.co/edit/Y5IZmPbrrO63YrL8uCkc?p=preview
You can also find useful examples of this approach in AngularJS documentation: http://docs.angularjs.org/api/ng.directive:ngInclude
yes you can separate the static view with the dynamic view, in actual this is what angularjs suggest.It is not required to move the scope of ng-app.
so you can do like this: menu is displayed as the static part
index.html
<body ng-app>
<ul class="menu">
<li>view1</li>
<li>view2</li>
</ul>
<div ng-view></div>
</body>
in your config file you can include your routing which page routes to which page and which controller to used on loading of any view.
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});

Resources