Ui-Router $state.go() does not refresh data - angularjs

I have a Product List state and Product Edit/Add state in my Angular app.
Product List data gets loaded in the controller (I didn't think I need resolve to be defined in state config) which gets data from an ngResource:
function InventoryListCtrl (myResource) {
var vm = this;
myResource.query(function (data) {
vm.products = data;
});
}
On Edit Controller, after I edit a product I get back to list state like this:
vm.product.$update().$promise;
$state.go('productList');
It doesn't load list with new data always, it shows old data in first run generally, then after I do second update and manually get back to list state it starts to refresh after each update.
I've tried this, but didn't work either:
vm.product.$update().$promise;
$state.go('productList', {}, { reload: true });
What am I missing?

I think you're loading the new state before the update has completed - try moving the state transition to after the update completion:
vm.product.$update().then(function(){
$state.go('productList', {}, { reload: true });
});

i think this should work for current state refresh.
$state.go($state.current, {}, {reload: true}); //second parameter is for $stateParams

I had the same problem with a list not refreshing after edit. Wrapping the $state.go in a $timeout function solved my problem.
$timeout(function(){
$state.go('publishers.list', {}, { reload: true });
},200);

Related

how to prevent ui-bootstrap pagination control from changing the url route

Within my application I have two views search and masternameserch these views are defined in app.js as:
$stateProvider
.state('search', {
url: '/',
controller: 'searchController',
controllerAs: 'search',
templateUrl: '/app/views/search.html'
})
.state('searchmasterName', {
url: '/searchmastername',
controller: 'searchMasterNameController',
controllerAs: 'masternameSearch',
templateUrl: '/app/views/searchmastername.html'
})
Within my views I have the ui-bootstrap pagination control setup as
<div class="text-center">
<uib-pagination ng-show="masternameSearch.pgTotalItems > 10" total-items="masternameSearch.pgTotalItems" ng-click="masternameSearch.pageChanged(); $event.stopPropagation();" ng-model="masternameSearch.pgCurrentPage" class="pagination-md" max-size="masternameSearch.pgMaxSize" boundary-links="true"></uib-pagination>
</div>
And within the controller I have the pageChanged() function setup as follows:
vm.pageChanged = function () {
var pageRequest = buildMasterNameSearchRequest(); //get cached request
pageRequest.pageFrom = vm.pgCurrentPage; //set page number to request
var currentPath = $state.current.name;
searchService.postSearchRequest(pageRequest).then(renderResults, onError);
$state.go('searchmastername',
{},
{
notify: false,
location: false,
inherit: false,
reload: false
});
$timeout(function () { location.hash = '#top' }, 1000);
}
The question I have is whenever clicking on the pagination control the underlying URL is always the root url. Therefore when I click on a pagination button the search executes but I am navigated back to the default main view which is wrong. As you can see from the code I first tried in the directive itself to change the onchange to an ng-click event and tried to stop propagation to stop the redirect through $event. This did not work. Second thing I tried was to call a state transition / state.go() in the pageChanged() function where I basically reload the view. This however does not work as it throws an error that the state cannot be found. Sadly this actually prevents the page from reloading or navigating to the main page so the error actually makes the page work as the end user might expect, but with errors generated around the missing state I know this isn't right.
Update: The error was generated from a type searchmastername and not searchmasterName.
Making this change fixed the error but still causes the site to redirect to the default view to load.
Can anyone provide an idea or ways to get the pagination control to not cause a navigation event by redirecting me to the default main view when ever clicked?
-cheers
After doing some more studying of this problem I thought the issue could be addressed by listening to the $rootScope for the stateChangeStart event and from there add a preventDefault() function to stop the navigation from occurring in the route which I did.
So the code now looks like this on the pageChanged() function
vm.pageChanged = function () {
var pageRequest = buildMasterNameSearchRequest(); //get cached request
pageRequest.pageFrom = vm.pgCurrentPage; //set page number to request
searchService.postSearchRequest(pageRequest).then(renderResults, onError);
$rootScope.$on('$stateChangeStart',
function(event) {
event.preventDefault();
});
$timeout(function () { location.hash = '#top' }, 1000);
}
While useful, using preventDefault() stops all further interaction with the page. Links would no longer work etc. I thought I had fixed but instead I had just stopped the event so the timeout never got called which was the culprit.
The real issue and I did it to my self was adding the timeout and using the location route #.
$timeout(function () { location.hash = '#top' }, 1000);
Using this function was actually (as designed) changing my route in my URL and navigating me to the main view. I needed to have the ability to scroll to the top so I changed the timeout function to look like this
vm.pageChanged = function () {
vm.showPager = false;
var pageRequest = buildMasterNameSearchRequest(); //get cached request
pageRequest.pageFrom = vm.pgCurrentPage; //set page number to request
searchService.postSearchRequest(pageRequest).then(renderResults, onError);
window.scrollTo(0, 0);
}
Using window.scroll accomplished the same scrolling effect but did not change the route.

How can I cause a state to be refreshed with ui-router?

I am on the state:
home.subjects.subject.exams.exam.tests.test
I delete a test and retrieved a new list of tests without the test I deleted in response.data.tests.
So now I want to go to this state:
this.$state.go('home.subjects.subject.exams.exam.tests', {
examId: this.exs.exam.examId,
subjectId: this.sus.subject.id,
tests: response.data.tests
});
But the router is thinking I already got all the resolves for the state so it does not try to repopulate the new list of tests.
Can someone tell me if it's possible to go to a state like this but have the resolves work.
Hope this makes sense.
There is an additional param that you can pass to go:
this.$state.go('home.subjects.subject.exams.exam.tests', {
examId: this.exs.exam.examId,
subjectId: this.sus.subject.id,
tests: response.data.tests
}, {
reload: true
});
See http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state for more details

How to implement filtering with Angular Ui-router

We want to implement pagination (or filtering) using ui-router. We don't want to reload controller each time next/prev parameters changed. We want to listen for an event and load data from API with new state parameters.
Code from our routes.js
$stateProvider.state('app.company.account.charges.index', {
url: '?before&after',
controller: 'ChargesCtrl',
templateUrl: 'app/charges.html',
reloadOnSearch: false,
params: {
before: { value: null, squash: true },
after: { value: null, squash: true },
}
});
our controller:
function ChargesCtrl() {
var loadCharges = function() {
Charge.query({before: $state.params.before, after: $state.params.after}).then(function(charges) {
$scope.charges = charges;
});
}
$scope.goNext = function() {
$state.go('app.company.account.charges.index', {before: $scope.pagination.before, after: null});
};
$scope.goPrevious = function() {
$state.go('app.company.account.charges.index', {after: $scope.pagination.after, before: null});
};
$scope.$on('state params were changed', function() {
loadCharges();
});
}
how can we track state params changes if $stateChangeSuccess is not raised because of reloadOnSearch is false.
P.S. now we just broadcast own event to solve this, but I'm looking for 'natural' solution :)
Ui Bootstrap has a really easy way to implement pagination. And it's also easy to integrate with Ui-router! This link will bring you to the pagination help :)
have fun coding
Thanks to #krish I have found the answer: Set URL query parameters without state change using Angular ui-router
And it's to use a hack with changing reloadOnSearch option to false before updating location params and then revert it back in $timeout.
However I think that using something like this is more explicit:
$scope.goNext = function() {
$state.go('app.company.account.charges.index', {before: $scope.pagination.before, after: null});
$scope.$emit('charges.paginated');
};
$scope.$on('charges.paginated', function(event) {
event.stopPropagation();
loadCharges();
});

Changing states but controller is not being called in angular js

I have a webpage which displays the user profile information from the database which is working fine, and another one in which user edits his/her information, which is edited in the database, which is also working. But after I change the data in the second webpage, I have changed the state to the first page using $state.go, which also seems to be working, but the newly updated data is not showing in this first page, the controller is not being called I think.
This is my controller of webpage which shows the userprofile :
.controller('myProfileCtrl', function (..parameters..) {
$scope.id = window.localStorage.getItem("profileId");
$scope.$root.loading = true;
$http.get('my link...')
.success(function (data) {
$scope.first_name = data[0].first_name;
$scope.middle_name = data[0].middle_name;
})
This is the controller of my second page which updates the user information :
.controller('editPersonalCtrl', function (..parameters..) {
$scope.saveChanges = function (user) {
$http.post('my link..', {
changeFirstName : new_first_name,
changeMiddleName : new_middle_name,
})
.success(function (data) {
$state.go('profile');//Go to the first webpage
$ionicHistory.nextViewOptions({
disableBack: true,
historyRoot: true
});
})
.error(function (data) {
alert("ERROR" + data);
});
}
The state changes but the newly updated data is not shown, I mean the controller of the first webpage is not working, otherwise it would have fetched the new data from the database and displayed it. The old data is showing.
replace
$state.go('profile');
with
$state.go('profile', {}, { reload: true });
It will force the to transit and than also it's not working you can do like
$state.go('profile', {}, {reload: true,notify: true});
This will force and also will broadcast $stateChangeStart and $stateChangeSuccess events. Here is the ref

Angular UI Router Reload Controller on Back Button Press

I have a route that can have numerous optional query parameters:
$stateProvider.state("directory.search", {
url: '/directory/search?name&email',
templateUrl: 'view.html',
controller: 'controller'
When the user fills the form to search the directory a function in the $scope changes the state causing the controller to reload:
$scope.searchDirectory = function () {
$state.go('directory.search', {
name: $scope.Model.Query.name,
email: $scope.Model.Query.email
}, { reload: true });
};
In the controller I have a conditional: if($state.params){return data} dictating whether or not my service will be queried.
This works great except if the user clicks the brower's forward and/or back buttons. In both these cases the state (route) changes the query parameters correctly but does not reload the controller.
From what I've read the controller will be reloaded only if the actual route changes. Is there anyway to make this example work only using query parameters or must I use a changing route?
You should listen to the event for succesful page changes, $locationChangeSuccess. Checkout the docs for it https://docs.angularjs.org/api/ng/service/$location.
There is also a similar question answered on so here How to detect browser back button click event using angular?.
When that event fires you could put whatever logic you run on pageload that you need to run when the controller initializes.
Something like:
$rootScope.$on('$locationChangeSuccess', function() {
$scope.searchDirectory()
});
Or better setup like:
var searchDirectory = function () {
$state.go('directory.search', {
name: $scope.Model.Query.name,
email: $scope.Model.Query.email
}, { reload: true });
$scope.searchDirectory = searchDirectory;
$rootScope.$on('$locationChangeSuccess', function() {
searchDirectory();
});
Using the above, I was able to come up with a solution to my issue:
controller (code snippet):
...var searchDirectory = function (searchParams) {
if (searchParams) {
$scope.Model.Query.name = searchParams.name;
$scope.Model.Query.email = searchParams.email;
}
$state.go('directory.search', {
name: $scope.Model.Query.name,
email: $scope.Model.Query.email,
}, { reload: true });
};...
$rootScope.$on('$locationChangeSuccess', function () {
//used $location.absUrl() to keep track of query string
//could have used $location.path() if just interested in the portion of the route before query string params
$rootScope.actualLocation = $location.absUrl();
});
$rootScope.$watch(function () { return $location.absUrl(); }, function (newLocation, oldLocation) {
//event fires too often?
//before complex conditional was used the state was being changed too many times causing a saturation of my service
if ($rootScope.actualLocation && $rootScope.actualLocation !== oldLocation && oldLocation !== newLocation) {
searchDirectory($location.search());
}
});
$scope.searchDirectory = searchDirectory;
if ($state.params && Object.keys($state.params).length !== 0)
{..call to service getting data...}
This solution feels more like a traditional framework such as .net web forms where the dev has to perform certain actions based on the state of the page. I think it's worth the compromise of having readable query params in the URL.

Resources