load html blocks with ngInclude when load other page with ngView - html

Actually I want to make some html blocks and load them via ngInclude and when I call a page via a controller, ngView shows the page that contain my html blocks
for example like this scaffold
root
index.html -----> contain ngView for loading pages
app.js
-------root/views
Dashboard.html ----> Contain dashboard's html blocks
--------------root/views/Dashboard
dashboard-profile.html ---->html block for dashboards
...
...
I tried the code below but it doesn't work
app.js
var demoApp = angular.module('sampleApp', ['ngRoute']);
demoApp.config(function ($routeProvider){
$routeProvider
.when('/dashboard',
{
controller: 'SimpleController1',
templateUrl: 'views/dashboard.html'
})
.when('/page',{
controller: 'SimpleController2',
templateUrl: 'Sources/views/page2.html'
})
.otherwise({ redirectTo: '/dashboard' });
});
demoApp.controller('myCtrl', function($scope) {
$scope.dashboardprofile = 'views/dashboard/dashboard-profile.html';
});
index.html
<body ng-app="sampleApp" >
<div ng-view ></div>
<!-- compiled and minified Bootstrap JavaScript -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-route.js"></script>
<script type="text/javascript" src="Sources/app2.js"></script>
</body>
dashboard.html
<div ng-include='dashboardprofile' ng-controller="myCtrl"></div>
dashboard-profile.html
Some divs and text
Thanks for your help

Try this..
var demoApp = angular.module('sampleApp', ['ngRoute']);
demoApp.config(function ($routeProvider){
$routeProvider
.when('/dashboard',
{
controller: 'myCtrl',
templateUrl: 'views/dashboard.html'
})
.when('/page',{
controller: 'SimpleController2',
templateUrl: 'Sources/views/page2.html'
})
.otherwise({ redirectTo: '/dashboard' });
});
demoApp.controller('myCtrl', function($scope) {
$scope.dashboardprofile = 'views/dashboard/dashboard-profile.html';
});

Related

when using routeparams in angular,templateurl not working?

https://plnkr.co/edit/oo05d6H6AxuJGXBAUQvr?p=preview
I have created an array of items and when I click on each item details page will be displayed ,for all the items in the array I have used same details page,can anyone look at my plunker and explain why the templateURL is not working when I click on an item?
var app = angular.module("myApp", ["ngRoute"]);
app.controller('mobileController', function($scope) {
$scope.items = [{
name: 'Iphone',
}, {
name: 'Oneplus'
}, {
name: 'Moto'
}];
});
app.config(function($routeProvider) {
$routeProvider
.when('/item/:itemName', {
templateUrl: 'details.html',
controller: 'ItemCtrl'
});
app.controller('ItemCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.itemName = $routeParams.itemName;
}
]);
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src="script.js"></script>
<body ng-app="myApp" ng-controller="mobileController">
<h2> Welcome to Mobile Store</h2>
<p>Search:<input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="item in items|filter:test">{{ item.name }}
</li>
</ul>
<div ng-view></div>
</body>
</html>
here is my details page
<!DOCTYPE html>
{{itemName}}
is it because of a mismatch?
.when('/item/:itemName', {
a href="/items/{{item}}"
there's an extra s there
Summary of problems:
Your ItemCtrl is currently defined inside your module's config function. Move it out of there
app.config(function($routeProvider) {
$routeProvider
.when('/item/:itemName', {
templateUrl: 'details.html',
controller: 'ItemCtrl'
});
}); // you were missing this
app.controller('ItemCtrl', ['$scope', '$routeParams',
Your route is /item/:itemName and since you're not using HTML5 mode, you need to create your href attributes with a # prefix. For example
ng-href="#/item/{{item.name}}"
Fixed demo here ~ https://plnkr.co/edit/rKHsBMFcXqJUGp8Blx7Q?p=preview

Ng-view or ui-view not displaying html page

I am relatively new to Angularjs, and am building a website. When I try to inject todo.html into the body tags of index.html nothing happens. I am not getting any errors in the console. I have read many of the similar posts to mine, and have already tried
Remove the ng-include from the body of index.html
Moved the links for angualrjs and bootstrap from the body of index.html to the head
Originally I used Ng-route but it did not work, so I implemented ui-router
I have tried both ng-route and ui-router,and both run without any errors. I don't think it has anything to do with either.
index.html
<html ng-app="todoApp">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Todo App</title>
<!-- Angular ans JS links-->
<script src="vendor/angular/angular.min.js"></script>
<script src="vendor/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="app/app.js"></script>
<script src="app/services/todo.service.js"></script>
<script src="app/controllers/todo.controller.js"></script>
<!-- <script src="vendor/angular-route/angular-route.min.js"></script>-->
<!--Jquery and Bootstrap Links-->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/js/bootstrap.min.js" integrity="sha384-VjEeINv9OSwtWFLAtmc4JCtEJXXBub00gtSnszmspDLCtC0I4z4nqz7rEFbIZLLU"
crossorigin="anonymous"></script>
<!-- css links -->
<link href="vendor/bootstrap-css-only/css/bootstrap.min.css" rel="stylesheet"><!-- load bootstrap -->
<link rel="stylesheet" href="assets/css/todoApp.css">
<link rel="stylesheet" type="text/css" href="assets/css/Header-Picture.css">
</head>
<body >
<div ng-include="'app/views/header.html'"></div>
<!--<div ng-include="'app/views/footer.view.html'"></div>
-->
<ui-view></ui-view>
<!--<div ui-view></div>-->
</body>
</html>
App.js
var todoApp = angular.module('todoApp', [
'ui.router'
]);
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'views/todo.html',
controller: 'TodoController'
})});
todo.controller.js
todoApp.controller('TodoController', ['$scope', 'Todos', function TodoController($scope, Todos) {
$scope.formData = {};
console.log("in the TodoController");
// when landing on the page, get all todos and show them
Todos.get()
.success(function(data) {
$scope.todos = data;
});
// when submitting the add form, send the text to the spring API
$scope.createTodo = function() {
if(!$scope.todoForm.$valid) {
return;
}
Todos.create($scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.todos.push(data);
});
};
// delete a todo after checking it
$scope.deleteTodo = function(id) {
Todos.delete(id)
.success(function(data) {
angular.forEach($scope.todos, function(todo, index){
if(todo.id == id) {
$scope.todos.splice(index, 1);
}
});
});
};
// when submitting the add form, send the text to the node API
$scope.saveTodo = function(todo) {
Todos.update(todo)
.success(function(data) {
$scope.editedTodo = {};
});
};
$scope.editedTodo = {};
$scope.editTodo = function(todo) {
$scope.editedTodo = todo;
}
$scope.revertTodo = function() {
$scope.editedTodo = {};
}
}]);
You should be using otherwise to force the first state to be loaded as below
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'todo.html',
})
$urlRouterProvider.otherwise('/');
});
Your index.html will look like
<div ng-include="'app/views/header.html'"></div>
<ui-view>
</ui-view>
LIVE DEMO
I added the code posted by #Aravind to my project which I belive was an improvement on my own and was correct. But the issue was the file path to the todo.html. The file path in the original was views/todo.html
the correct path is app/views/todo.html
My original code:
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'views/todo.html',
controller: 'TodoController'
})});
Current Working Code
todoApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('todo', {
url: "/",
templateUrl: 'app/views/todo.html',
})
$urlRouterProvider.otherwise('/');
});

Show/Hide elements on website for certain pages

I am using AngularUI Router to navigate content on my website. I have some webpages that show the header/footer navigation and some that do not. I want to be able to detect what my current page is and insert the HTML for the header/footer if needed.
Here is my current router
angular.module('app', ['ui.router'])
.config(['$urlRouterProvider', '$stateProvider',
function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'partials/home.html',
controller: 'homeCtrl'
})
.state('about', {
url: '/about',
templateUrl: 'partials/about.html',
controller: 'aboutCtrl'
})
.state('contact', {
url: '/contact',
templateUrl: 'partials/contact.html',
controller: 'contactCtrl'
})
.state('create', {
url: '/create',
templateUrl: 'partials/create.html',
controller: 'createCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'partials/login.html',
controller: 'loginCtrl'
})
}]);
For the html I have this
<html ng-app="app">
<body>
<!-- *********** HEADER ************* -->
<div ng-include=""></div>
<!-- ********** CONTENT *********** -->
<div ui-view></div>
<!-- **************** FOOTER ****************** -->
<div ng-include="'partials/standard_footer.html'"></div>
</body
</html>
For the webpages create and login I do not want to show the header and footer, but I am not sure how to do that.
I want to do something like this,
<div ng-if="!login && !create" ng-include="'standard_header.html'"></div>
How can I achieve this?
You can expose $state on the $rootScope and that will make it accessible in your webpage.
You can then simply check for state.current.name != 'login'
Like below:
Exposing the current state name with ui router
Edit:
Working Plunker of what i meant: https://plnkr.co/edit/JDpCo3fTePobuX9Qoxjn
You're almost there. Just add a flag in the params of the appropriate states:
.state('create', {
url: '/create',
templateUrl: 'partials/create.html',
controller: 'createCtrl',
params: {
hideHeaderAndFooter: true
}
})
.state('login', {
url: '/login',
templateUrl: 'partials/login.html',
controller: 'loginCtrl',
params: {
hideHeaderAndFooter: true
}
})
And then inject the $stateParams service in your controllers. Every property of the params object will be exposed as a property of the object this service returns:
loginCtrl.$inject = ['$scope', '$stateParams']
function loginCtrl($scope, $stateParams) {
$scope.hideHeaderAndFooter = $stateParams.hideHeaderAndFooter
}
Then you can use ng-if just the way you meant to use it:
<div ng-if="!hideHeaderAndFooter" ng-include="'standard_header.html'"></div>

Edit HTML outside ng-view on route change

I want to change some HTML in the navbar upon a route change, using the routing information. I can almost get it to work with the code below, but the data is not parsed as HTML when arriving in the DOM. I tried using the $sce service, but that didn't really get me anywhere.
If there are any other (better) ways of editing the HTML on route change, then please let me know.
HTML:
<nav>
<div ng-controller="BrandCtrl">
<div class="nav-brand">
{{brand}}
</div>
</div>
</nav>
<div ng-view></div>
JS:
var app = angular.module("app", ['ngRoute']);
app.controller("BrandCtrl", function($scope, $route) {
$scope.$on('$routeChangeSuccess', function() {
var html = $route.current.html;
$scope.brand = html;
});
});
app.config(function ($routeProvider) {
$routeProvider
.when('/next-page', {
templateUrl: 'partials/next-page.html',
controller: 'BrandCtrl',
html: '<h3>New brand</h3>'
});
You should be changing the HTML via the 'views' in the routes.
$stateProvider.state('app',{url: 'someurl',
views: {
'topnav': { templateUrl: 'path/to/some/html',
controller: 'navcontroller'},
'mainContent': {templateUrl: 'path/to/some/other/html',
controller: 'contentcontroller'} }
});
In your HTML you would have multiple views:
<div ui-view="topnav"></div>
<div ui-view="mainContent"></div>

Using ngRoute with 'controller as' syntax in angularJS

I have the following config and controllers
.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'page-home.html',
controller: 'homeController',
controllerAs: 'hctrl'
})
.when('/about', {
templateUrl: 'page-about.html',
controller: 'aboutController',
controllerAs: 'actrl'
})
.when('/contact', {
templateUrl: 'page-contact.html',
controller: 'contactController',
controllerAs: 'cctrl'
});
})
.controller('homeController', function(){
this.pageClass = 'page-home'
})
.controller('aboutController', function(){
this.pageClass = 'page-about'
})
.controller('contactController', function(){
this.pageClass = 'page-contact'
});
My problem comes when I use in in the index.html.
<div class="page {{pageClass}}" ng-view></div>
Since I'm not using $scope, just writing {{pageClass}} won't work. How can I get around this using the controller as syntax?
Edit
I got a couple of good answers. I also discovered an alternate way to do this if you want to name your controllerAs values with different names: hctrl, actor and ctrl (like my code above):
You could do this in the html:
<div class="page {{hctrl.pageClass || actrl.pageClass || cctrl.pageClass}}" ng-view></div>
A good approach towards this problem is by setting the pageClass as a configuration in the routes definition and then create a directive that gets these definitions to be applied as whatever you want them to be (of course within the scope where the directive is applied to).
DEMO
Javascript
Define your route configuration with data key-value object.
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'page-home.html',
controller: 'homeController',
controllerAs: 'hctrl',
data: {
pageClass: 'page-home'
}
})
.when('/about', {
templateUrl: 'page-about.html',
controller: 'aboutController',
controllerAs: 'actrl',
data: {
pageClass: 'page-about'
}
})
.when('/contact', {
templateUrl: 'page-contact.html',
controller: 'contactController',
controllerAs: 'cctrl',
data: {
pageClass: 'page-contact'
}
});
})
Create a directive that sets these data with the directive's controller.
.directive('routeData', function() {
return {
controller: 'RouteDataController',
controllerAs: 'RouteData',
bindToController: true
}
})
.controller('RouteDataController', function($rootScope, $route) {
var self = this;
$rootScope.$on('$routeChangeSuccess', setCurrentRouteData);
setCurrentRouteData();
function setCurrentRouteData() {
angular.extend(self, $route.current.$$route.data || {});
}
})
In your index.html apply the directive itself and access the directive's controller to get the data values.
<div ng-view route-data class="page {{ RouteData.pageClass }}"></div>
Specify the controller as name
<div class="page {{hctrl.pageClass}}" ng-view></div>
Whatever you wrote in the controllerAs value need to be prepended to the variable, like {{actrl.pageClass}}