AngularJS $location replace() replacing last history entry also - angularjs

On my AngularJS application I need to save only state changes in the browser history. That's why when I'm changing parameters of $location, I'm using replace() method.
For example, When I'm accessing /page1, it is save in the history. 'centre' parameter is added automatically with replace() so it doesn't add a new history entry:
$location.search('centre', hash).replace();
Every time I move a map, 'centre' changes.
When I go to /page2, the new entry in the history is created. When I move map, 'centre' changes.
The thing is that when I press BACK button, I'm going to /page1 but I need to keep 'centre' the same as it was before, but it changes to what was saved together with history entry of /page1.
How would I fix this issue?
I tried to add:
$window.history.replaceState({}, '', $location.absUrl());
After I do replace(), but didn't work.

I found calling the search & replace inside a 0ms timeout ensures it happens in a separate digest cycle from the main state change and prevents the previous state being replaced.
Something like:
$timeout(function() {
$location.search('centre', hash).replace();
}, 0);

This is how I solved this.
First, we need to save search result as previous and current:
$rootScope.$on('$locationChangeStart', function (event, toURL, fromURL) {
if ($rootScope.search.current) {
$rootScope.search.previous = $rootScope.search.current;
}
$rootScope.search.current = $location.search();
});
Then we need to always change the actual location we are in at the moment.
$rootScope.$on('$locationChangeSuccess', function (event, toURL, fromURL) {
$rootScope.actualLocation = $location.path();
});
And if back of forward button was pressed, center must be changed in the URL (using previous search results) without pushing a new history entry.
$rootScope.$watch(function () { return $location.path() }, function (newLocation, oldLocation) {
if ($rootScope.actualLocation === newLocation) {
$location.search('center', $rootScope.search.previous.center).replace();
}
});

I had the same problem and could only get it working by using the native history api, like so:
window.history.replaceState(hash, null, $location.absUrl());

Related

If user 'touches' form inputs on profile & forgets to save: show `POP UP` when they click SideMenu icon

I've tried to come up with some sort of "error checker/validation" for my users IF they forget to Save the edits they made on their profiles.
The user enters the Profile.html state. They start to update some of their info (i.e name, phone number, etc.). INSTEAD of pressing the SAVE CHANGES button they navigate away from the Profile state by clicking the SideMenu icon at the top left of their mobile screen.
Since the form is technically now consider to be "$dirty". I've tried to use this angular property at first but I couldn't really get the results I wanted so I tried my luck with $watch..
ProfileController.js
$rootScope.isFormDirty = false;//global variable 'isFormDirty'->inject in controller.js (toggleLeftSideMenu())
$scope.$watch('updateDriverProfileInfo', function(newValue, oldValue) {//new & oldValue = ng-model when form is 1st 'viewed' is dirty
//http://tutorials.jenkov.com/angularjs/watch-digest-apply.html
if (newValue !== oldValue) {
// console.log("updatingg")
$rootScope.isFormDirty = true;
}
}, true);
Angular docs on $watch
Maybe I should of made a factory or Service for this now that I think about it but at the time I used $rootScope so that I can set a global variable isFormDirty on this controller and use it on the General Controller that holds the Side Menu's logic in this Ionic app.
controller.js (this is where the Controller for the SideMenu is)
$scope.sidemenuIsOpen = false;
$scope.toggleLeftSideMenu = function() {//ng-click from menu.html
$scope.sidemenuIsOpen = !$scope.sidemenuIsOpen;
if ($scope.sidemenuIsOpen && $rootScope.isFormDirty) {
var confirmPopup = $ionicPopup.confirm({
title: 'Changes were not saved',
template: 'Do you want to save your changes?',
});
confirmPopup.then(function(res) {
if (res) {
console.log('Run updateDriverProfile()');
} else {
console.log('Allow user to continue w/o changes');
}
});
}
};
That's basically the gist of my code. It actually "works" but I have identified a pattern and this is where I need your assistance to either suggest a whole different method to accomplish this or perhaps some refactoring tips for this current code.
The Pop up does show when the user clicks on the Side Menu button BUT I don't think it really matters if the form is $dirty or not..
The bigger issue is that the Pop up starts showing regardless if you are trying to leave the profile.html view or any other view for that matter.
When I wrote this code I was under the impression that the Pop up and toggleLeftSideMenu functions would ONLY work on the Profile view since I am "watching" the updateDriverProfileInfo object and I also created that global variable to use between the Menu Controller and Profile Controller.
you need to have a good understanding on ionic Lifecycle, try with any of the below events
$scope.$on('$ionicView.leave', function(){
// Anything you can think of
});
$scope.$on('$ionicView.beforeLeave', function(){
// Anything you can think of
});
$scope.$on('$ionicView.unloaded', function(){
// Anything you can think of
});
find more information here http://www.gajotres.net/understanding-ionic-view-lifecycle/

backbone.history.naviguate trigger router staying on the same page

My problem is pretty simple.
I start on /app, when I click on some button I trigger /report with
Backbone.history.navigate('report',{trigger: true, replace: true});
Then I'm on /report page. No problem.
I have the same button on /report and I would like to trigger router route "report" when i click on it. It seems it's not working because I'm already on the asked page.
Any idea how I should proceed ?
thanks a lot
Backbone.history.navigate('report',{trigger: true, replace: true});
You should not be using this to render/reload your application views.This is not recommended.
Rather you should have a controller object (a js object) which extends Backbone.Events
Define a callback for the for the route "/report" as follows:
var MyAppBus = _.extend({},Backbone.Events);
MyAppBus.on("report",function(payLoad){
// 1.Load the data
// 2.Create an instance of the view passing the loaded data.
// (In your case, you could also pass an instance of the view in the payload
// and update the data alone in the view instance.)
// 3.Render the view.
// 4.Call the router navigate function with trigger set to false to
// update the url on a need basis.
});
Now, in the event/router callback you can do something like this:
MyAppBus.trigger("report",payLoad);
Where payLoad in the event callback could be:
var payLoad = {};
payLoad.view = viewInstance;

ng-grid with manually handle page index changed

I have an example of ng-grid server side pagination from here : http://ddeloy.com/angular-ng-grid-example/server-side-page/index.html
However as the original purpose of pagination.. i do NOT want to load the entire records from the server.. I am passing the page size and index to the server code so I need to be able to handle the click event of page index change (previous and next page button).. how can i do this with ng-grid?
in the same link that you have provided you can see that the pageSize and index are handled in a watch, so you can call your server side function from there, something like this:
$scope.$watch('pagingOptions', function () {
$http.post('/get_records', {"page_size": $scope.pagingOptions.pageSize,
"page_index": $scope.pagingOptions.currentPage}
).success(function (serverPagedData) {
$scope.myData = serverpagedData;
$scope.pagingOptions.totalServerItems = serverPagedData.length;
if (!$scope.$$phase) {
$scope.$apply();
}
});
}, true);
Cheers!

Angular $scope losing child data in certain situation

I'm having an issue where, when I simply console.log($scope.visitors) my data is fine, but when I console.log($scope.visitors) and then try to open a AngularUI Bootstrap dialog, the $scope.visitors.optionalFields object is empty.
Now, I've spent some time trying to replicate the issue in jsbin and I wasn't able to get it to happen, so it may be difficult to answer; just hoping somebody might have an idea what could be causing it.
So I have an array of objects like this:
$scope.visitors = [
{
company:"one",
optionalFields: {
passportNumber:"ppt",
contactNumber:"tel",
licensePlate:"1234"
},
firstName:"some",
lastName:"guy",
}
]
I ng-repeat through these with visitor in visitors and each one has a button with ng-click="editVisitorDialog(visitor)"
Now, if I make editVisitorDialog like this:
$scope.editVisitorDialog = function (visitor) {
console.log($scope.visitors);
console.log(visitor);
}
Then both $scope.visitors and visitor look good, they have all of their properties.
However, if I simply add to this function (i.e., the log calls are still at the top of the function), each visitor in $scope.visitors will have an empty optionalFields object.
$scope.editVisitorDialog = function (visitor) {
console.log($scope.visitors); // missing the optionalFields items
console.log(visitor); // missing the optionalFields items
var modalInstance = $modal.open({
templateUrl: 'app/checkin/edit_visitor/edit_visitor.html',
controller: EditVisitorController,
resolve: {
visitor: function () {
return visitor;
}
}
});
modalInstance.result.then(function (result) {
console.log(result)
}, function () {
});
}
When you call console.log() with an object it doesn't really log the object. It's rather like an inspection tool where you can see the current state, not the state at the time console.log() was called.
Try console.log(visitor.optionalFields.passportNumber) instead and I guarantee that it will log "ppt" (in your example).
That in turn means that somehwere in the added code the optional fields get lost.

still the navigate triggers and upate my url, the method is not calling

In my backbone app, i use the requirejs to load the js files. as well i need different views, there is no.of links are there in my drop down menu. according to the drop down menu i a adding the #url example:
http://localhost:85/bino/html/interface-I.html#projectName/project11
the navigate method works fine and updating the url, also whenever i copy and paste this url to any other browser / refresh with current hash state my router methods works fine.
But click on link in the drop down menu not working, the method not calling... what would be the reason and how can i fix this..?
my code: main js file (part of code)
var extender = _.extend({},backBone.Events);
var params ={
boardHolder :$('.boardHolder'),
column :3,
space :30,
extender :extender
};
var listApp = new routerer(params);
backBone.history.start();
extender.bind("list:selected",function(post){
listApp.navigate(post.category+'/'+post.filter);
});
my router code :
define(["backBone","singleton","listCollection","listView","listViews"],function(Backbone,singleton,listCollection,listView,listViews){
singleton.router = Backbone.Router.extend({
routes:{
"" :"appView",
"post" :"postView",
"projectName/:id" :"projectNameView",
"assignedTo/:id" :"assignedToView",
"sortBy/:id" :"sortByView"
},
initialize:function(params){
this.params = params;
this.collection = new listCollection;
console.log('i am called');
},
hashView:function(){
console.log('from hash view');
},
appView:function(){
var that = this;
// var defaultApp = new listCollection();
this.collection.fetch({
success:function(data){
new listViews({model:data,params:that.params})
}
})
},
projectNameView:function(thisView){ // not calling not sync
console.log('called',thisView); // on click not works
},
assignedToView:function(thisView){ // not calling not sync
console.log(thisView); // on click not works
},
sortByView:function(thisView){ // not calling not sync
console.log(thisView); // on click not works
}
});
return singleton.router;
})
thanks in advance.
navigate only updates the url, you also have to call the route function by setting the trigger option to true. If you'd like to update the URL without creating an entry in the browser's history, also set the replace option to true.
listApp.navigate(post.category+'/'+post.filter);
would become
listApp.navigate(post.category+'/'+post.filter, {trigger: true});

Resources