UI Router - Remember scroll position when transition between states - javascript

I have two views: a start page and a details page.
The start page is long and I want the user to get back to it's last position when it goes back from a details page.
If the user hits the back button it does exactly that but if I link it with ui-sref or an a tag to start it will always go to the top of page.
Is it possible to have the back button functionality in all cases?
<a ui-sref="start">Back</a> - (goes to top)
Back - (wanted behaviour)
I created a quick Plunker to illustrate my example.
http://plnkr.co/edit/z8kdD7ONkL4bML4IaFNz?p=preview
Please click the Launch in a separate window button to get the expected behaviour.

Here's what I came up with. When navigating back from the detail view to the list view, pass the ID of the item that was being shown. Then scroll that item in the list back into view.
http://plnkr.co/edit/tWv4UNbBdSbes3XKEcYw?p=preview
html:
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<title>ui router test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div ui-view class="main-view"></div>
<script id="templates/start.html" type="text/ng-template">
<p>Return to {{value}}</p>
<div class="start">
<div ng-repeat="i in getNumber(30) track by $index" class="box" id="item_{{$index}}" ui-sref="detail({id:$index})">
{{$index}}
</div>
</div>
</script>
<script id="templates/detail.html" type="text/ng-template">
<div class="detail">
Page: {{id}} <br><br>
<button ui-sref="start({id:id})">Start by sref</button>
<button ng-click="goBack()">Back by history</button>
Link
</div>
</script>
<script type="text/javascript" src="http://code.angularjs.org/1.3.14/angular.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.14/angular-animate.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.14/angular-touch.js"></script>
<script type="text/javascript" src="https://cdn.cdnhttps.com/cdn-libraries/angular-ui-router/0.2.13/angular-ui-router.min.js"></script>
<script type="text/javascript" src="ui-router-extras.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
js:
var app = angular.module('myApp', ['ngAnimate', 'ui.router', 'ct.ui.router.extras.dsr']);
app.config(function ($stateProvider,$urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state('start', {
url: "/?id",
templateUrl: "templates/start.html",
controller: 'StartCtrl',
deepStateRedirect: true
})
.state('detail', {
url: "/detail/:id",
templateUrl: "templates/detail.html",
controller: 'DetailCtrl',
deepStateRedirect: true
})
});
app.controller('StartCtrl', function($scope, $stateParams, $location, $anchorScroll) {
$scope.getNumber = function(num) {
return new Array(num);
}
$scope.value = $stateParams.id;
if($scope.value) {
$location.hash("item_" + $scope.value);
$anchorScroll();
}
});
app.controller('DetailCtrl', function($scope, $stateParams) {
$scope.id = $stateParams.id;
$scope.goBack = function() {
window.history.back();
};
});

Related

Angularjs variable out of ng-view

I want to have particular variable for menu to know which class to be active. Up to now I know how to set variable inside ng-view but I want to keep my menu out of that view. If I set variable in function in controller isn't visible outside of ng-view and that is exactly what I want to, to be visible. I try with rootscoope but I couldn't manage. If someone can help me my code is like this:
index.html
<!DOCTYPE html>
<html lang="en" ng-app="example">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="libs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<link href="assets/css/main.css" rel="stylesheet">
<title>Example</title>
</head>
<body>
<div class="container-fluid main-header">
<div class="main-menu-active">First page</div>
<div class="main-menu">Second page</div>
</div>
<div ng-view class="main-body"></div>
<script src="libs/jquery/dist/jquery.min.js"></script>
<script src="libs/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<link href="libs/ng-dialog/css/ngDialog.min.css" rel="stylesheet">
<link href="libs/ng-dialog/css/ngDialog-theme-default.css" rel="stylesheet">
<script src="libs/ng-dialog/js/ngDialog.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/mainCtr.js"></script>
</body>
</html>
app.js
(function () {
'use strict';
angular
.module('example', ['ngRoute','ngDialog'])
.config(function ($routeProvider,$httpProvider) {
$routeProvider.when('/', {
controller: 'mainCtr',
controllerAs: 'mCtr',
templateUrl: 'app/views/firstPage.html'
});
$routeProvider.when('/second', {
controller: 'mainCtr',
controllerAs: 'mCtr',
templateUrl: 'app/views/secondPage.html'
});
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}).run(function($http, $httpParamSerializerJQLike) {
//decode json on every submit form
$http.defaults.transformRequest.unshift($httpParamSerializerJQLike);
})
})();
controller:
(function() {
'use strict';
angular
.module('example')
.controller('mainCtr', mainCtr);
mainCtr.$inject = ['$window','$routeParams','ngDialog','$timeout'];
function mainCtr($window,$routeParams,ngDialog,$timeout) {
var vm = this;
vm.firstPage = firstPage;
vm.secondPage = secondPage;
function firstPage() {
vm.test = 'This is first page';
}
function secondPage() {
vm.test = 'This is second page';
}
}
})();
I want to have access to variable vm.test in <div class="container-fluid main-header">
I would make a Controller around the ng-view which hold the value(s):
<body ng-controller="OuterController">
<div class="container-fluid main-header">
<div class="main-menu-active">First page</div>
<div class="main-menu">Second page</div>
</div>
<div ng-view class="main-body"></div>
...
</body>
and if you want to share data between the controllers in ng-view directive use a service.
So I've made a plunker to illustrate, how data sharing is accomplished: https://plnkr.co/edit/axekEgrFwnm93aFXoMKd
So the basic idea is to use a service and in someway either by button click as in the question or automatically in contoller as plunker, set the shared value.
Service
app.service('commonInfomation', function() {
return {
test: ''
};
});
Inner controller
app.controller('FirstCtrl', function($scope, commonInfomation) {
commonInfomation.test = "Hello from first page";
});
Outer controller
app.controller('MainCtrl', function($scope, commonInfomation) {
$scope.commonInfomation = commonInfomation;
});
View
<body ng-controller="MainCtrl">
<h2>{{commonInfomation.test}}</h2>
<div class="container-fluid main-header">
<a href="#/">
<div class="main-menu-active">First page</div>
</a>
<a href="#/second">
<div class="main-menu">Second page</div>
</a>
</div>
<div ng-view class="main-body"></div>
</body>
Module
var app = angular.module('plunker', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'firstpage.html',
controller: 'FirstCtrl'
})
.when('/second', {
templateUrl: 'secondpage.html',
controller: 'SecondCtrl'
})
});

location path search with param not navigate to next page

I just want to pass a parameter to the next page (edit page) by clicking edit button. I tried the following code but it's not working. The URL just shown like below quote but the page shows blank and the controller is not loaded also. What is wrong here?
http://localhost:8080/#/group/edit?id=586351373b6bba91152ab744
View
<md-button class="md-raised md-primary" ng-click="doEdit(item._id)" title="Edit">Edit</md-button>
Route
$routeProvider.when('/group/edit', {
templateUrl: 'template/group_edit.html',
controller: 'GroupEditCtrl'
})
Controller
$scope.doEdit = function (id) {
$location.path('/group/edit').search({id: id});
}
Maybe some more code could be useful to understand what's going wrong, this simple snippet seems to do the job.
angular.module('BlankApp', ['ngMaterial', 'ngRoute']);
angular
.module('BlankApp')
.config(['$routeProvider', setupRoutes])
.controller('ListController', ['$scope', '$location', ListController])
.controller('GroupEditCtrl', ['$scope', '$location',GroupEditCtrl]);
function setupRoutes($routeProvider) {
$routeProvider.
when("/", { controller: "ListController", templateUrl: "list.html" });
$routeProvider.when('/group/edit', {
templateUrl: 'edit.html',
controller: 'GroupEditCtrl'
})
}
function ListController($scope, $location) {
$scope.item = {_id: 123}
$scope.doEdit = function (id) {
$location.path('/group/edit').search({id: id});
}
}
function GroupEditCtrl($scope, $location) {
$scope.locationParam = $location.search().id
$scope.goBack = function() {
$location.path('/');
}
}
<html lang="en" >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Angular Material style sheet -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
</head>
<body ng-app="BlankApp" ng-cloak>
<ng-view></ng-view>
<script type="text/ng-template" id="list.html">
<md-button class="md-raised md-primary" ng-click="doEdit(item._id)" title="Edit">Edit</md-button>
</script>
<script type="text/ng-template" id="edit.html">
ehy edit! id: <pre>{{locationParam | json}}</pre> <br/>
<md-button class="md-raised md-primary" ng-click="goBack()" title="Back">Back</md-button>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
<!-- Angular Material Library -->
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
</body>
</html>

How to solve angularjs Uncaught Error: [$injector:modulerr]?

I am developing a single page web application using AngularJS' ng-view and ng-template directives. But when I run it my browser show this type [1]: http://i.stack.imgur.com/TPuPo.png of error.
Here is my script block with main module and routing configuration.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AngularJS - Views</title>
<!--AngularJs Library-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.min.js"></script>
</head>
<body>
<h2 style="text-align: center;">Simple Application using AngularJS - Views</h2><hr><br>
<!--Start AngularJS App-->
<div ng-app="myApp">
<p>Add Student</p>
<p>View Students</p>
<div ng-view></div>
<!--Script for Add Student-->
<script type="text/ng-template" id="addStudent.htm">
<h2>This is the view of Add Student</h2>
{{message}}
</script>
<!--Script for View Students-->
<script type="text/ng-template" id="viewStudent.htm">
<h2>This is the view of all students</h2>
{{message}}
</script>
</div>
<!--End AngularJS App-->
<!--App Necessary Scripts-->
<script>
var myApp = angular.module("myApp", ['ngRoute']);
myApp.config(['routeProvider',function ($routeProvider) {
$routeProvider.
when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudent', {
templateUrl: 'viewStudent.htm',
controller: 'ViewStudentController'
}).
otherwise({
redirectTo: '/addStudent'
});
}]);
myApp.controller('AddStudentController', function ($scope) {
$scope.message = "This page will be used to display add student form!!";
});
myApp.controller('ViewStudentController', function($scope){
$scope.message = "This page will be used to display all students!!";
});
</script>
</body>
</html>
what can I do to fix it?
Here's your working code. Also here's a CodePen example, I reorganize the code to make it more comfortable, please review it, study it and compare it for learning purpose. http://codepen.io/alex06/pen/rrzRbE?editors=1010
<html ng-app="mainApp">
<head>
<title>Angular JS Views</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div>
<p>Add Student</p>
<p>View Students</p>
<div ng-view></div>
</div>
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
<script type = "text/ng-template" id = "viewStudents.htm">
<h2> View Students </h2>
{{message}}
</script>
<script>
(function(){
'use strict'
angular
.module('mainApp', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
})
.when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
})
.otherwise({
redirectTo: '/addStudent'
});
}])
.controller('AddStudentController', function($scope) {
$scope.message = "This page will be used to display add student form";
})
.controller('ViewStudentsController', function($scope) {
$scope.message = "This page will be used to display all the students";
});
})();
</script>
</body>
</html>
Just change the following line:
myApp.config(['routeProvider',function ($routeProvider) {
To
myApp.config(['$routeProvider',function ($routeProvider) {
I think this is what you missed.
Define config as this:--
myApp.config(function ($routeProvider) { $routeProvider
Rather than:-- myApp.config(['routeProvider',function ($routeProvider) {
$routeProvider.

Angular ui modal unexpected behavior

I'm trying to implement a modal from angular ui bootstrap. After I implemented it on my web application, I got an unexpected behavior which is the modal does show up after I clicked the text, but what shows up is not the path that I wanted but rather the navbar of the web app.
Here's the code
index.html
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<title></title>
<base href='/'>
<!-- load bootstrap from CDN and custom CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- JS -->
<!-- load angular and angular-route via CDN -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
<script src="app.js"></script>
<script type="text/javascript" src="controller.js"></script>
</head>
<body>
<header>
<div class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<span class="glyphicon glyphicon-book"></span>Testing App
</div>
<ul class="nav navbar-nav navbar-right" ng-controller="ModalController">
<li>Write</li>
</ul>
</div>
</div>
</header>
<div ng-view></div>
</body>
</html>
app.js
angular.module('MyApp', ['ngRoute', 'ui.bootstrap'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
});
$locationProvider.html5Mode(true);
});
controller.js
angular.module('MyApp')
.controller('HomeController', function($scope, $location) {
$scope.data = "Hello Angular";
})
.controller('ModalController', function($scope, $location, $modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: function() {
},
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
home.html
<div class="container">
<h1>Awesome {{ data }}</h1>
</div>
modal.html (The path that the modal suppose to show);
<h1>Need to show this actually</h1>
The picture, what shows up after i clicked the text that trigger the modal event
Added this:
<script type="text/ng-template" id="modal.html">
<h1>Need to show this actually</h1>
</script>
right after
<ul class="nav navbar-nav navbar-right" ng-controller="ModalController">
and it works in plunker:
http://plnkr.co/edit/bPuemujbTiX7U8AnY607?p=preview

Why the template BLANK ? Angularjs

I don't know why my template is not being rendered anymore. I get a blank page. It worked before then after some tweaks it stopped working. I've reversed most of the code and i still don't get why is not working . There is no kind of error in the console. How am I supposed to debug this kind of behavior ?
Here is the controller
'use strict';
/* Controllers */
var crmControllers = angular.module('crmControllers', []);
crmControllers.controller('TimelineCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
var emailsId
emailsId = $routeParams.emailsId;
$http.get('http://local.sf.com:8080/timeline/API?emailsId=' + emailsId,
{withCredentials: true}).success(function(timelines){
angular.forEach(timelines, function(timeline) {
var inboxIfr
inboxIfr = 'http://local.sf.com:8080/messages/inbox?email='+
timeline.Email+'&toEmail='+timeline.ToEmail+'&subject='+timeline.Subject
timeline.inboxIfr = inboxIfr
$scope.inboxIfr = inboxIfr
console.log(inboxIfr);
});
});
}]);
inboxIfr shows up in the console log which means that the loop is happening but it's just not rendered.
Html
<body>
<ul ng-repeat="timeline in timelines">
<p>hello <p/>
<iframe class="container well well-small span6"
style="height: 400px;"
ng-src="{{timeline.inboxIfr}}"></iframe>
</ul>
app.js
'use strict';
/* App Module */
var crmApp = angular.module('crmApp', [
'ngRoute',
'crmControllers',
]);
crmApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/timeline/:emailsId', {
templateUrl: 'partials/time.html',
controller: 'TimelineCtrl'
}).
otherwise({
redirectTo: '/timeline:emailsId'
});
}]);
index.html
<!doctype html>
<html lang="en" ng-app="crmApp">
<head>
<meta charset="utf-8">
<title>SF</title>
<!--<<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">-->
<!--<link rel="stylesheet" href="css/app.css">-->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="js/controllers.js"></script>
<!--<script src="bower_components/angular-bootstrap/ui-bootstrap.min.js"></script>-->
<!--<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>-->
<script src="js/app.js"></script>
<html>
</head>
<body>
<div ng-view></div>
</body>
</html>
Edit : I've added some dummy text above ng-repeat="timeline in timelines"> and it's being rendered so the real issue is that nothing is rendered inside the ng-repeat loop .
Edit: I've reduced time.html to this and it's still not being rendered . Only the first paragraph is being rendered ("I can see this")
<p>I can see this</p>
<li ng-repeat="timeline in timelines">
<p>I can't see this <p/>
</li>
The default route isn't pointing to a valid route:
app.js:
.otherwise({
redirectTo: '/timeline:emailsId'
});
shoud be:
.otherwise({
redirectTo: '/timeline/:emailsId'
});
EDIT: More HTML/Angular mistakes:
Remove body tags in Angular templates.
Don't use ng-repeat with <ul> tags. Rather use it with <li> or other block-elements like <div>
You use ng-repeat with the scope variable timelines, but you never set $scope.timelines

Categories

Resources