In this plunk you have two ui-router states, a parent and a child. When the child is invoked by clicking on the link, since it has the option reload: true it is always reloaded. This is fine, but the problem is that the parent state is reloaded as well. Try to click on the 'Populate 11' link several times and you'll see that the parent timestamp also changes.
How can I reload only the child?
Javascript:
var app = angular.module("app", ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state('state1', {
templateUrl: 'state1.html',
controller: function($scope) {
$scope.theTime1 = Date.now();
}
})
.state('state1.state11', {
templateUrl: 'state11.html',
controller: function($scope) {
$scope.theTime11 = Date.now();
}
});
});
It's actually very simple.
Don't use reload because that does exactly what you found. It reloads everything for the route.
Instead, add a parameter to your child route and every time the link is clicked make sure to change that parameter. That will force the child state to be reloaded.
I updated your plunk with an example. I just added a num parameter and increase a count variable each time the link is clicked.
http://plnkr.co/edit/qTA39rrYFYUegzuFbWnc?p=preview
A changing parameter as Mathew Foscarini suggested, is (for sure) way to go. There could be also another solution, technique with state reloader. Below, and in this updated plunker we can see simplified version, but we can even pass some params there to make it more general
.state('state1.reloader', {
controller: function($state) {
$state.go('state1.state11')
}
})
And we can call it like:
// instead of this
<a href="#" ui-sref="state1.state11" ui-sref-opts="{reload: true}">
// we can do this
<a href="#" ui-sref="state1.reloader" >
Check it here
Related
For some reason I cannot redirect to the next state.
genAPISettings.view.html only contains:
<div ui-view></div>
The controller only contains this:
app.controller('AdminDashboardGeneralAPISettingsController', ['$scope',
'$state', 'llApi', function ($scope, $state, llApi) {
}]);
The state:
.state('dashboardContainer.GeneralAPISettings', {
url: 'GeneralAPISettings',
templateUrl: 'views/AdminDashboard/genAPISettings/genAPISettings.view.html',
controller: 'AdminDashboardGeneralAPISettingsController'
}
Using $state.go("dashboardContainer.GeneralAPISettings", {}); only shows me a flash of redirecting to the state, but then quickly redirects me to the precious state. Using <a ui-sref = "dashboardContainer.GeneralAPISettings">General API</a> does not redirect the page at all. However, changing the url manually to /GeneralAPISettings does correctly change to this state.
You might have an ui-sref on the container, causing that sref to trigger instead of the one that you wanted.
For example, if your code was like this:
<div ui-sref="state1"><a ui-sref"state2">Link</a></div>
When clicking on the Link, you might expect to go to state2, but instead go to state1.
Source: I've encountered a similar problem.
I want to temporarily change the browser url when the ui bootstrap modal is opened ( The page behind should remain as is, only the url changes ). When the modal is closed the url should be reverted back to the original one.
Steps :
User loads the page
url : xyz.com/home
User clicks a link opens a modal
url : xyz.com/detail/123
possible solution : changing url with html5 push state
problem : Angular ui-router tries to run its routes as per the changed url, eventually changing the background page.
User closes the modal
url : xyz.com/home
possible solution : html5 pop state
problem : Reloads the background page, which kills the purpose
Example implementation : Pinterest pins and their pin details popup.
You can use ui-router-extras sticky state to solve your problem. There is simple example with modal by the link. You should create two named views, one for main content (background) and one for modal.
<div ui-view="app"></div>
<div ui-view="modal"></div>
Mark the state, from what you want to access to modal as sticky: true in route definition.
.state('main', {
abstract: true,
url: '/',
templateUrl: '_layout.html'
})
.state('main.index', {
url: '',
sticky: true,
views: {
'app': {
templateUrl: 'index.html'
}
}
})
.state('main.login', {
url: 'login/',
views: {
'modal': {
templateUrl: 'login.html'
}
}
})
Also add an event for stateChangeSuccess:
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
if ((from.views && !from.views.modal) || !from.views) {
$rootScope.from = from;
$rootScope.fromParams = fromParams;
}
});
so, when you need to close modal, you can just
$state.go($rootScope.from, $rootScope.fromParams);
There is small problem for that solution. If you reload page on the modal state, then the app ui-view will be empty.
This can be achieved by having a nested state and triggering the modal using onEnter callback:
$stateProvider
.state('contacts', {
url: '/home',
templateUrl: 'home.html',
controller: function($scope, MyService){
$scope.contacts = MyService.getContacts();
}
})
.state('contacts.details', {
url: "^/details/:id", // using the absolute url to not have the "/home" prepended
onEnter: function($state, $uibModal) {
var modal = $uibModal.open({
templateUrl: 'details.html',
controller: function($scope, $stateParams, MyService) {
// get data from service by url parameter
$scope.contact = MyService.getContact($stateParams.id);
}
});
modal.result.finally(function() {
$state.go('^'); // activate the parent state when modal is closed or dismissed
});
}
});
This technique is described in the ui-router's FAQ.
Here the plunk. In this example the modal's scope is created as a child of the $rootScope - the default $uibModal's behavior when no scope is passed to it. In this case we should use the service in the modal's controller to obtain the data by url parameter.
To have master and details URLs look like these - xyz.com/home and xyz.com/detail/123 - we should use the absolute URL (^/details/:id) in the child state.
Using this solution you can open the detail URLs directly and still have both, master and detail states, activated properly, so sharing the detail URL is possible.
I think you can achive that with ngSilent module
https://github.com/garakh/ngSilent
using $ngSilentLocation.silent('/new/path/');
(once you open modal and again after closing it)
Managed to implement this using https://github.com/christopherthielen/ui-router-extras/tree/gh-pages/example/stickymodal
I debated a while on this but I got a Plunk that reproduce it.
I have a state "Contact" that get loaded by default. with $state.transitionTo
Inside that state I have some views, they all get loaded and everything work.
If I click to change the state to "Home" by default or by "ui-sref" and in the "Home" state/template I have ui-sref="contacts". When we click back to set the state to contacts it should work, but all the sub views are now not being called properly.
It seems that when ui-sref call the state this one behave differently that when it is loaded by default.
Why $state.transitionTo(''); seems to work differently than ui-sref.
<script>
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /
$urlRouterProvider.otherwise("/")
$stateProvider
.state('home', {
templateUrl: 'home.html',
controller: function($scope){
}
})
.state('contacts', {
templateUrl: 'contacts.html',
controller: function($scope){
}
})
.state('contacts.list', {
views:{
"":{
template: '<h1>Contact.List Working wi no Data defined.</h1>'
},
"stateSubView":{
template: '<h2>StateSubView Working</h2>'
},
"absolute#":{
template: '<h2>Absolute item</h2>'
}
}
});
});
myapp.controller('MainCtrl', function ($state) {
$state.transitionTo('contacts.list');
})
Q2:
Why is the Absolute tag that is under contact work when I add the view in the Index, but is not working when it is inside the contact.html file. Absolute reference work only with the Index and not if called everywhere?
"absolute#":{
template: '<h2>Absolute item</h2>'
}
I saw that in index.html you have an empty ui-view tag. What do you expect to go there? I think you can not do this. The router just doesn't know with which state (home or contacts) it should replace. Apparently it picks the second one (contacts). I'd suggest to put url: '/' in the home state and you'll see the difference.
This is for sure one issue.
Other than that:
You can't simply access views from contacts.list in contacts afaik.
The empty ui-view work as a wild card and can be use to switch across multiple route even if we have nested element. But if we have a nested view contact.list it can only be access if we put the whole path in ui-sref="contacts.list" because the list child of contact cannot be access only by using ui-sref="contacts"
It works when called via ui-sref
<a class="button" ui-sref="main.create">
but when it's called using ng-click and $stage.go, it's called and renders the page but my $urlRouterProvider.otherwise will override the DOM again. I noticed it when I debugged step by step. It maybe thinks that main.create is a non-existent url.
here is the code and function for ng-click.
Create Object
and here is create() function
$scope.create = function() {
$state.go('main.create');
};
It's calling $state.go('main') when ng-click="create()" is used. But before it calls $state.go('main'), I see the proper main.create page render in DOM. I wrote that "IF" statement to handle non-existent url so they get redirected back to main page. Here is my config.js.
.state('main', {
url: '/',
views: {
'#': {
templateUrl: 'app/main/main.html',
controller: 'MainController'
},
'content#main' : {
templateUrl: 'app/main/main.display.html'
}
}
})
.state('main.create', {
url: '/create',
views: {
'content#main' : {
templateUrl: 'app/main/main.create.html'
}
}
})
$urlRouterProvider.otherwise(function ($injector) {
var Session = $injector.get('Session');
var $state = $injector.get('$state');
if (Session.isAuthenticated()) {
$state.go('main'); // <-- this is what gets called when using ng-click and after main.create partial gets rendered
} else {
$state.go('login');
}
});
This is occurring because you are triggering an action and a route on the same anchor tag. In <a href="#" ng-click="create()">, you don't need both href and ng-click to be present. change it to <a ng-click="create()">, or if having the href is necessary, set it to empty, like <a href="" ng-click="create()">.
Claies is correct that the problem is stemming from having both an href and an ng-click on the same tag, but the proper solution is to make sure your $scope.create() function returns a false boolean value immediately after the call to $state.go, then the href can be whatever you want and will get ignored.
In general (even outside angular), if an anchor tag has both an href and a click event handler, it will execute both of them, first the click event handler(s), then the href -- unless the click event handler returns a false value, then it effectively cancels the href execution. As you noted, the different browsers execute href="#" and/or href="" differently, but it won't be an issue if your $scope.create() function returns false.
I am trying to implement a tabbed interface akin to this: http://odetocode.com/blogs/scott/archive/2014/04/14/deep-linking-a-tabbed-ui-with-angularjs.aspx
However, on my state change, the controller of the parent state seems to be reinitialized (or a new $scope is created?)
There are two major differences between the example plunkr and my project.
I use a parameter in my url
I resolve different data on the state change for each tab (removing this does nothing).
I am not using ui-bootstrap for the tabs but am triggering a $state.go on ng-click of the tab.
I experimented with the above plunkr and added a dropdown to the parent state; however the parent dropdown values seem to persist when the child states change. I am not too concerned with the child states and will probably end up using sticky states anyways.
I am using wondering if I am doing something fundamentally wrong before I try and add another package to my project.
here is a rough plunkr of what I am trying to do: http://plnkr.co/edit/TmRQN5K8OEc8vHG84G5z?p=preview
here is my config:
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.when('/main',
function ($state) {
$state.go('parent.tab1', { main_id: '00008' });
});
$stateProvider
//Handle States Here
.state('parent', {
abstract: true,
url: '/parent?main_id',
templateUrl: "main.html",
controller: 'Main_Controller',
resolve: {
//Calls to API
}
})
.state('parent.tab1', {
url: "/applications",
templateUrl: "tab1.html",
controller:'Tab1Ctrl',
resolve: {
//Get some different data from an API
},
})
.state('parent.tab2', {
url: "/phasing",
templateUrl: "tab2.html",
controller: 'Tab2Ctrl',
resolve: {
//More API Data
}
});
});
I've made your plunker working here
$urlRouterProvider
//.when('/main',
.when('',
function ($state) {
$state.go('parent.tab1', { main_id: '00008' })
});
Also there is a change in main.html, which does not use ng-controller any more. We just have to pass the proper Controller name
$stateProvider
//Handle States Here
.state('parent', {
abstract: true,
url: '/parent?main_id',
templateUrl: "main.html",
controller: 'MainController',
resolve: {
//Calls to API
}
})
...
// MainController
// these two names should fit
app.controller("MainController", function($rootScope, $scope, $state) {
So now, it is working, and let's discuss
I use a parameter in my url
I resolve different data on the state change for each tab (removing this does nothing).
I am not using ui-bootstrap for the tabs but am triggering a $state.go on ng-click of the tab.
Quick answers:
parameter in url exists, e.g. #/parent/tab1?main_id=8000
resolve is trigerred for each controller if controller is reinstantiated. That happens when we navigate to that state (among tabs)
no need to use $state.go, I used:
a snippet:
<a ui-sref="parent.tab1({main_id:'00008'})"> go to tab1 with main_id '00008'</a><br />
<a ui-sref="parent.tab2({main_id:'00008'})"> go to tab2 with main_id '00008'</a><br />
<a ui-sref="parent.tab3({main_id:'00008'})"> go to tab3 with main_id '00008'</a><br />
Check it here