angular ionic, how to reload controller on link in the markup - angularjs

I want to reload the controller I'm linking to in a menu in an ionic angular app. How do I declare the link in the markup so that it refreshes the destination route every time the link is clicked?
I saw this bit of code
$state.go($state.current, {}, {reload: true});
Which I suppose I can wrap in a controller method but I would prefer to do it in the markup if possible.

Wrap it in a function in your controller:
$scope.reload = function () {
$state.go($state.current, {}, { reload: true });
}
Then use it in your view:
<button ng-click="reload()">Reload</button>

Related

reload: true works only once

I am trying to pass parameters from one view to another in my anulgar/ionic app.
in the volCompute view ($stateParams is declared):
if ($stateParams.modelLine){
console.log('receiving', $stateParams.modelLine.id, $stateParams.modelLine.modelStrict)
$scope.data.chosenModel = $stateParams.modelLine.modelStrict;
}
in the compareview:
$state.go('app.volCompute', { modelLine: test[0] }, {reload: true});
but it works only one time, if I go back and forth between the two views the code in volCompute is not run.
It seems like the reload: true is only executed once.
Can you help please ?
There are few more details how to understand ionic caches
What is the difference between $ionicView.enter and cache:false
ui.router not reloading controller
And I would suggest to use the event hook here $ionicView.enter or $ionicView.afterEnter
$scope.$on('$ionicView.enter', function(){
// Coding
});
there is the link to doc
In your routes file:
$stateProvider.state('myState', {
cache: false,
url : '/myUrl',
templateUrl : 'my-template.html'
})
Or inidividually in an <ion-view> tag:
<ion-view cache-view="false">
...
</ion-view>

how to call a controller in ionic?

In my ionic blank app, i have two html file index.html and category.html.
i write the controller for index.html in app.js like
.controller('AppCtrl',function($scope){
$scope.menu = function() {
console.log('yesytest');
window.location = "category.html";
};
})
this is working fine and after reaching the category page i create another controller in app.js
controller('categoryCtrl',function($scope){
console.log('ffffffffff');
$scope.beauty = function() {
console.log('yesytest');
window.location = "categorydetails.html";
};
});
i add a ng-click function on a button inside category.html but when i click on that button it is not calling the controller?
You can define your controller either on :
- defining it on your ui router state
.state('camera',{
url:"/camera",
cache: false,
controller:"CameraCtrl",
templateUrl:'app/views/loading/index.html'
})
Or by defining it into tour template category.html
<div ng-controller="categoryCtrl"> .... </div>
This is standard AngularJS feature, nothing special with ionic
If you use this :
.state('category',{
url:"/category",
controller:"categoryCtrl",
templateUrl:'templates/category.html'
})
You can use ui-sref="stateId" to do redirection
Example:
<a ui-sref="category"></a>
..Hi Kindly route your controller just define them..This might help.. --> http://learn.ionicframework.com/formulas/navigation-and-routing-part-1/ ^_^
//app.js
.state('category',{
url:"/category",
controller:"categoryCtrl",
templateUrl:'templates/category.html'
})
//index.html
<a ng-href="#/category"></a>

How to reload AngularJS controller and resolver?

I am using Angular's UI Router and I am looking to create a $scope function (ultimately to pass to the view to have a ng-click call it) to reload a controller and its associated resolver. How would I do this?
I've tried this but it doesn't seem to reload the resolver:
$scope.reloadMe = function() {
$state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true });
};
just inject $route into the controller and call $route.reload so the code would look like:
$scope.reloadMe = function () {
$route.reload();
};
You can read the documentation here: https://docs.angularjs.org/api/ngRoute/service/$route
You can inject $injector and load $state to reload. Here I put two examples, you can use one of them.
function MyController($injector, data) {
$injector.get('$state').reload(); // this reload all states and controllers scopes
// or
$injector.get('$state').go($state.current, {}, {reload: true}); // second parameter is for $stateParams
}
Otherwise, in case i need to reload the page, i use javascript
window.location.reload()
This question is asked here

How to reload the current state?

I'm using Angular UI Router and would like to reload the current state and refresh all data / re-run the controllers for the current state and it's parent.
I have 3 state levels: directory.organisations.details
directory.organisations contains a table with a list of organisations. Clicking on an item in the table loads directory.organisations.details with $StateParams passing the ID of the item. So in the details state I load the details for this item, edit them and then save data. All fine so far.
Now I need to reload this state and refresh all the data.
I have tried:
$state.transitionTo('directory.organisations');
Which goes to the parent state but doesn't reload the controller, I guess because the path hasn't changed. Ideally I just want to stay in the directory.organisations.details state and refresh all data in the parent too.
I have also tried:
$state.reload()
I have seen this on the API WIKI for $state.reload "(bug with controllers reinstantiating right now, fixing soon)."
Any help would be appreciated?
I found this to be the shortest working way to refresh with ui-router:
$state.go($state.current, {}, {reload: true}); //second parameter is for $stateParams
Update for newer versions:
$state.reload();
Which is an alias for:
$state.transitionTo($state.current, $stateParams, {
reload: true, inherit: false, notify: true
});
Documentation: https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_reload
This solution works in AngularJS V.1.2.2:
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
That would be the final solution. (inspired by #Hollan_Risley's post)
'use strict';
angular.module('app')
.config(function($provide) {
$provide.decorator('$state', function($delegate, $stateParams) {
$delegate.forceReload = function() {
return $delegate.go($delegate.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
};
return $delegate;
});
});
Now, whenever you need to reload, simply call:
$state.forceReload();
for ionic framework
$state.transitionTo($state.current, $state.$current.params, { reload: true, inherit: true, notify: true });//reload
$stateProvider.
state('home', {
url: '/',
cache: false, //required
https://github.com/angular-ui/ui-router/issues/582
Probably the cleaner approach would be the following :
<a data-ui-sref="directory.organisations.details" data-ui-sref-opts="{reload: true}">Details State</a>
We can reload the state from the HTML only.
#Holland Risley 's answer is now available as an api in latest ui-router.
$state.reload();
A method that force reloads the current state. All resolves are
re-resolved, controllers reinstantiated, and events re-fired.
http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state
$state.go($state.current, $stateParams, {reload: true, inherit: false});
$scope.reloadstat = function () { $state.go($state.current, {}, {reload: true}); };
if you want to reload your entire page, like it seems, just inject $window into your controller and then call
$window.location.href = '/';
but if you only want to reload your current view, inject $scope, $state and $stateParams (the latter just in case you need to have some parameters change in this upcoming reload, something like your page number), then call this within any controller method:
$stateParams.page = 1;
$state.reload();
AngularJS v1.3.15
angular-ui-router v0.2.15
Silly workaround that always works.
$state.go("otherState").then(function(){
$state.go("wantedState")
});
For angular v1.2.26, none of the above works. An ng-click that calls the above methods will have to be clicked twice in order to make the state reload.
So I ended up emulating 2 clicks using $timeout.
$provide.decorator('$state',
["$delegate", "$stateParams", '$timeout', function ($delegate, $stateParams, $timeout) {
$delegate.forceReload = function () {
var reload = function () {
$delegate.transitionTo($delegate.current, angular.copy($stateParams), {
reload: true,
inherit: true,
notify: true
})
};
reload();
$timeout(reload, 100);
};
return $delegate;
}]);
Everything failed for me. Only thing that worked...is adding cache-view="false" into the view which I want to reload when going to it.
from this issue https://github.com/angular-ui/ui-router/issues/582
Not sure why none of these seemed to work for me; the one that finally did it was:
$state.reload($state.current.name);
This was with Angular 1.4.0
I had multiple nested views and the goal was to reload only one with content.
I tried different approaches but the only thing that worked for me is:
//to reload
$stateParams.reload = !$stateParams.reload; //flip value of reload param
$state.go($state.current, $stateParams);
//state config
$stateProvider
.state('app.dashboard', {
url: '/',
templateUrl: 'app/components/dashboard/dashboard.tmpl.html',
controller: 'DashboardController',
controllerAs: 'vm',
params: {reload: false} //add reload param to a view you want to reload
});
In this case only needed view would be reloaded and caching would still work.
I know there have been a bunch of answers but the best way I have found to do this without causing a full page refresh is to create a dummy parameter on the route that I want to refresh and then when I call the route I pass in a random number to the dummy paramter.
.state("coverage.check.response", {
params: { coverageResponse: null, coverageResponseId: 0, updater: 1 },
views: {
"coverageResponse": {
templateUrl: "/Scripts/app/coverage/templates/coverageResponse.html",
controller: "coverageResponseController",
controllerAs: "vm"
}
}
})
and then the call to that route
$state.go("coverage.check.response", { coverageResponse: coverage, updater: Math.floor(Math.random() * 100000) + 1 });
Works like a charm and handles the resolves.
You can use #Rohan answer https://stackoverflow.com/a/23609343/3297761
But if you want to make each controller reaload after a view change you can use
myApp.config(function($ionicConfigProvider) { $ionicConfigProvider.views.maxCache(0); ... }
If you are using ionic v1, the above solution won't work since ionic has enabled template caching as part of $ionicConfigProvider.
Work around for that is a bit hacky - you have to set cache to 0 in ionic.angular.js file:
$ionicConfigProvider.views.maxCache(0);
I had this problem it was wrecking my head, my routing is read from a JSON file and then fed into a directive. I could click on a ui-state but I couldn't reload the page. So a collegue of mine showed me a nice little trick for it.
Get your Data
In your apps config create a loading state
Save the state you want to go to in the rootscope.
Set your location to "/loading" in your app.run
In the loading controller resolve the routing promise and then set the location to your intended target.
This worked for me.
Hope it helps

AngularJs: Reload page

<a ng-href="#" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
I want to reload the page. How can I do this?
You can use the reload method of the $route service. Inject $route in your controller and then create a method reloadRoute on your $scope.
$scope.reloadRoute = function() {
$route.reload();
}
Then you can use it on the link like this:
<a ng-click="reloadRoute()" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
This method will cause the current route to reload. If you however want to perform a full refresh, you could inject $window and use that:
$scope.reloadRoute = function() {
$window.location.reload();
}
**Later edit (ui-router):**
As mentioned by JamesEddyEdwards and Dunc in their answers, if you are using angular-ui/ui-router you can use the following method to reload the current state / route. Just inject $state instead of $route and then you have:
$scope.reloadRoute = function() {
$state.reload();
};
window object is made available through $window service for easier testing and mocking, you can go with something like:
$scope.reloadPage = function(){$window.location.reload();}
And :
<a ng-click="reloadPage" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
As a side note, i don't think $route.reload() actually reloads the page, but only the route.
location.reload();
Does the trick.
<a ng-click="reload()">
$scope.reload = function()
{
location.reload();
}
No need for routes or anything just plain old js
Similar to Alexandrin's answer, but using $state rather than $route:
(From JimTheDev's SO answer here.)
$scope.reloadState = function() {
$state.go($state.current, {}, {reload: true});
}
<a ng-click="reloadState()" ...
If using Angulars more advanced ui-router which I'd definitely recommend then you can now simply use:
$state.reload();
Which is essentially doing the same as Dunc's answer.
My solution to avoid the infinite loop was to create another state which have made the redirection:
$stateProvider.state('app.admin.main', {
url: '/admin/main',
authenticate: 'admin',
controller: ($state, $window) => {
$state.go('app.admin.overview').then(() => {
$window.location.reload();
});
}
});
Angular 2+
I found this while searching for Angular 2+, so here is the way:
$window.location.reload();
This can be done by calling the reload() method in JavaScript.
location.reload();
It's easy enough to just use $route.reload() (don't forget to inject $route into your controller), but from your example you could just use "href" instead of "ng-href":
<a href="" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
You only need to use ng-href to protect the user from invalid links caused by them clicking before Angular has replaced the contents of the {{ }} tags.
On Angular 1.5 - after trying some of the above solutions wanting to reload only the data with no full page refresh, I had problems with loading the data properly. I noticed though, that when I go to another route and then I return back to the current, everything works fine, but when I want to only reload the current route using $route.reload(), then some of the code is not executed properly. Then I tried to redirect to the current route in the following way:
$scope.someFuncName = function () {
//go to another route
$location.path('/another-route');
};
and in the module config, add another when:
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/first-page', {
templateUrl: '/first-template',
controller: 'SomeCtrl'
}).when('/another-route', {//this is the new "when"
redirectTo: '/first-page'
});
}])
and it works just fine for me. It does not refresh the whole page, but only causes the current controller and template to reload. I know it's a bit hacky, but that was the only solution I found.
<a title="Pending Employee Approvals" href="" ng-click="viewPendingApprovals(1)">
<i class="fa fa-user" aria-hidden="true"></i>
<span class="button_badge">{{pendingEmployeeApprovalCount}}</span>
</a>
and in the controller
$scope.viewPendingApprovals = function(type) {
if (window.location.hash.substring(window.location.hash.lastIndexOf('/') + 1, window.location.hash.length) == type) {
location.reload();
} else {
$state.go("home.pendingApproval", { id: sessionStorage.typeToLoad });
}
};
and in the route file
.state('home.pendingApproval', {
url: '/pendingApproval/:id',
templateUrl: 'app/components/approvals/pendingApprovalList.html',
controller: 'pendingApprovalListController'
})
So, If the id passed in the url is same as what is coming from the function called by clicking the anchor, then simply reload, else folow the requested route.
Please help me improve this answer, if this is helps. Any, suggestions are welcome.
This can be done by calling the reload() method of the window object in plain JavaScript
window.location.reload();
I would suggest to refer the page. Official suggestion
https://docs.angularjs.org/guide/$location

Resources