Angular routes not refreshing the view - javascript

I try to create an app with angular, and somehow the child state in not loading.
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url : "/",
templateUrl: "/admin/home/"
})
.state('users', {
url : "/users/",
templateUrl: "/admin/users",
controller : function ($stateParams) {
console.log($stateParams);
console.log("users");
}
})
.state('users.new', {
url : "^/users/user/",
templateUrl: "/admin/users/new",
controller : function () {
console.log("users.new");
}
})
.state('users.user', {
url : "^/users/user/:uuid",
templateUrl: function ($stateParams) {
console.log($stateParams);
return "/admin/users/" + $stateParams.uuid
},
controller : function () {
console.log("users.user");
}
});
When I visiting the page
/users/user/55d8b1c706387b11480d60c1
I see the request to load the page, but only the "users" controller got executed.
This problem appears only with child states, switching between parent state working without problems.
I Using the latest versions of angular and ui-routes.
any ideas?

Please read this DOC
You mistake is in hierarchy. Child states use parent template as root and try find nested <ui-view>
You may add abstract state user without url, with empty template <ui-view></ui-view>, for nested viws. Then rename user, to E.G. user.index, it works for me
1st (It may works)
$stateProvider
.state('home', {
url : "/",
templateUrl: "/admin/home/"
})
.state('users', {
template: "<ui-view></ui-view>",
})
.state('users.index', {
url : "/users/",
templateUrl: "/admin/users",
controller : function ($stateParams) {
console.log($stateParams);
console.log("users");
}
})
.state('users.new', {
url : "^/users/user/",
templateUrl: "/admin/users/new",
controller : function () {
console.log("users.new");
}
})
.state('users.user', {
url : "^/users/user/:uuid",
templateUrl: function ($stateParams) {
console.log($stateParams);
return "/admin/users/" + $stateParams.uuid
},
controller : function () {
console.log("users.user");
}
});
2nd way is USE absulutly named views E.G.
views: {
"": { templateUrl: 'pages/menu.html' }, // relative noName view
"header": { templateUrl: "pages/header.html"}, //relative named view
"content#": { // Absolute name
template: "<ui-view></ui-view>",
controller: 'AuthController'}
}

Related

Dynamic template Angular UI-Router

I'm trying to load a navbar according to the user.
To do this, I need to set a dynamic template, but I can't see my $rootScope
$stateProvider
/*Login*/
.state('login', {
url: '/',
data: {pageTitle: 'Inicio de sesión.'},
resolve: {},
views: {
'navbar': {
templateUrl: null,
controller: null
},
'body': {
templateUrl: "views/login.html",
controller: 'LoginController'
}
}
})
.state('home', {
url: '/home',
data: {pageTitle: 'Home.'},
views: {
'navbar': {
templateUrl: "views/navbar.html", //here dynamic template
controller: null
},
'body': {
templateUrl: "views/inicio.html",
controller: null
}
}
})
.state('perfil', {
url: '/perfil',
data: {pageTitle: 'Perfil de usuario.'},
views: {
'navbar': {
templateUrl: function (sessionProvider) {
var sessionFactory = sessionProvider.path();
return sessionFactory;
}, // this return a tring, but don't load anything
controller: null
},
'body': {
templateUrl: "views/usuario/perfil.html",
controller: 'UsuarioController'
}
}
});
i've tried use a service to load the data, but it didnt work, also tried to load it from the localStorageService, but don't display anything.
is there a single way to load it ?
There are features for this, like templateUrl and templateProvider. See all details here:
Trying to Dynamically set a templateUrl in controller based on constant
E.g. this could be an example of templateProvider used isntead of the 'templateUrl' static path
templateProvider: function(CONFIG, $templateRequest) {
console.log('in templateUrl ' + CONFIG.codeCampType);
var templateName = 'index5templateB.html';
if (CONFIG.codeCampType === "svcc") {
templateName = 'index5templateA.html';
}
return $templateRequest(templateName);
},

URL Route Parameters in AngularJS ui-router

I want to be able to reload just the nested view of my application and attached a route parameter on so that I can have URL routing in my application. I cannot figure out how to do this, I initially had it working with a query like this:
$location.search('userId', user._id);
//http://localhost:9000/#/user/?userId=123456789
My desired URL is below, with the userId = 123456789
http://localhost:9000/#/user/123456789
My app.js file
$stateProvider
.state('index', {
url: '/',
views: {
'#' : {
templateUrl: 'views/layout.html'
},
'top#index' : {
templateUrl: 'views/top.html',
controller: function($scope, $state) {
$scope.userLogOut = function() {
$state.go('login');
};
}
},
'left#index' : { templateUrl: 'views/left.html' },
'main#index' : { templateUrl: 'views/main.html' }
}
})
.state('index.user', {
url: 'user:userId',
templateUrl: 'views/user/user.html',
controller: 'UserCtrl'
})
.state('index.user.detail', {
url: '/',
views: {
'detail#index' : {
templateUrl: 'views/user/details.html',
controller: 'DetailCtrl'
}
}
})
In my controller:
$state.reload('index.user.detail', {userId: $scope.user._id});
As you are using ui-router you can use $state.go('index.user', { userId: {{yourid}} });
To allow the query string parameter to work using ui-router write your state like this,
.state('index.user', {
url: 'user/?userId=:param',
templateUrl: 'views/user/user.html',
controller: 'UserCtrl'
})
That would allow this to work,
//http://localhost:9000/#/user/?userId=123456789
Without the query string parameter (your desired URL) would be this,
.state('index.user', {
url: 'user/:userId',
templateUrl: 'views/user/user.html',
controller: 'UserCtrl'
})
http://localhost:9000/#/user/123456789

UI router change templateUrl on click

Im trying to create a dynamic UI router when everytime you click a button it needs to return the templateUrl with the $stateParams.currentFloor changes only so it can get updated in the view on the screen.
Currently I have:
My setup:
app.config(function ($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
views: {
"menu-view": {
templateUrl: 'partials/menu.html'
},
"map-view": {
controller: 'mapViewController',
templateUrl: function ($stateParams) {
return 'partials/floors/floor-' + $stateParams.currentFloor + '.html'
}
}
}
})
});
My controller what needs to hold the data and pass it in the templateUrl function
app.controller('mapViewController', function ($scope, $stateParams) {
$scope.currentFloor = $stateParams.currentFloor;
$scope.currentFloor = 1;
$scope.addOne = function () {
$scope.currentFloor = $scope.currentFloor + 1;
return $stateParams.currentFloor = $scope.currentFloor;
};
});
And just simple a function what adds +1 to the scope everytime on a click
<button ng-click="addOne()"></button>
I think I'm pretty close but I have a hard time passing the data from my controller to the function what needs to change the templateUrl
Check the updated plunker here
One possible solution :
var app = angular.module('testTool', ['ui.router'])
.config(function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/1');
$stateProvider
.state('home', {
url: '/:currentFloor',
views: {
"menu-view": {
templateUrl: 'menu.html'
},
"map-view": {
templateUrl: function ($stateParams) {
return 'floor-' + $stateParams.currentFloor + '.html'
},
controller: 'mapViewController'
},
}
})
})
.controller('mapViewController', function($scope, $stateParams, $state) {
$scope.addOne = function() {
$state.go('home', {currentFloor : parseInt($stateParams.currentFloor) + 1}, {reload: true})
};
});
Add param 'currentFloor in url params (url:'/:currentFloor'). Then reload state with this params : $state.go('home', {currentFloor : 2}, {reload: true})
Option reload:true is important for ui router reload the state when your are on the same state.
I suggest you to use resolve function if you need to do some work between $stateParams and object in your scope.
Try to add $state.go($state.current, {}, {reload: true}) after changing $stateParams.

Error: Could not resolve 'storysolo' from state 'index'

I have my index.php page with a ui-sref link as follows
<a ui-sref="storysolo({ storyId: headline.nid })">
I have my main js file loading the angular code as follows
var rebelFleet = angular.module("CougsApp", ["ui.router","ngAnimate", "ui.bootstrap", "ngSanitize", "slick","CougsApp.headlines","CougsApp.story","CougsApp.recentstories" ]);
rebelFleet.config(function($stateProvider) {
// For any unmatched url, redirect to /state1
$stateProvider
.state('index', {
url: "",
views: {
"navViewPort": { templateUrl: '/components/nav/nav.html'
},
"contentViewPort": {
templateUrl: '/components/headlines/headlines.html',
controller: "headlinesCtrl"
},
"eventsViewPort": { templateUrl: '/components/scroller/scroller.html' },
"bottomContentViewPort": { templateUrl: '/components/recentstories/recentstories.html',
controller: "recentstoriesCtrl"
},
"rightsideViewPort": { templateUrl: '/components/social/social.html' },
"footerViewPort": { templateUrl: '/components/footer/footer.html' }
}
})
Then I have my story.js file trying to load with it's own routing. as follows
var ywing = angular.module('CougsApp.story', ["ui.router"]);
ywing.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('storySolo', {
url: '/story/:storyId',
views: {
"navViewPort": { templateUrl: '/components/nav/nav.html'
},
"contentViewPort": {
templateUrl: '/components/story/story.html',
controller: "storyCtrl"
},
"footerViewPort": { templateUrl: '/components/footer/footer.html' }
}
})
});
So when I load my page and click on the ui-sref link I get this error
Could not resolve 'storysolo' from state 'index'
my order of files being loaded is as follows
angular.js,
angular-sanitize.js,
angular-ui-router.js,
rebelFleet.js, (the main js file)
story.js
I'm guessing I'm doing something wrong with the way the routes are being loaded and UI-Router hates it. Any help would be much appreciated.
There is a working example
Believe or not, it is very simple - it is about case sensitivity. State names must fit on the 1) definition as well on the 2) call side
// small solo
<a ui-sref="storysolo({ storyId: headline.nid })">
// capitalized Solo
$stateProvider.state('storySolo', {...
so just use one or the other, e.g.:
// not small solo
<a ui-sref="storySolo({ storyId: headline.nid })">
// the same name here
$stateProvider.state('storySolo', {...
Check the example here

AngularJS UI Router data persists when navigating from grand-child to parent

I am having weird issue probably caching issue while navigating from grand-child(/dashboard/1/production) to parent(/dashboard).
Following are few screenshots:
The selections i.e Delphi-UI and production shouldn't persists.
Following is my snippet of application config:
$stateProvider
.state('root', {
url: '/',
views: {
'header': {
templateUrl: 'ngapp/templates/header.html'
}
}
})
// dashboard routes
.state('root.dashboard', {
url: 'dashboard',
views: {
'content#' : {
templateUrl: 'ngapp/home/templates/dashboard.html',
controller: 'DashboardCtrl',
controllerAs: 'vm'
}
}
})
.state('root.dashboard.app', {
url: '/{id:int}',
views: {
'body#root.dashboard' : {
templateUrl: 'ngapp/home/templates/dashboard-body.html',
controller: 'DashboardBodyCtrl'
}
}
})
.state('root.dashboard.app.env', {
url: '/:name',
views: {
'body#root.dashboard' : {
templateUrl: 'ngapp/home/templates/env-content.html',
controller: 'EnvContentCtrl'
}
}
});
And DashboardCtrl is:
controllers.controller('DashboardCtrl', ['$scope', '$http', '$state', '$timeout', 'appsFactory', function($scope, $http, $state, $timeout, appsFactory) {
$scope.envs = [];
$scope.deps = [];
$scope.envBtnText = $scope.appBtnText = "Choose here";
$scope.headerTitle = "Environment Configuration And Management";
$scope.appStatus = {
isopen: false
};
$scope.envStatus = {
isopen: false
};
appsFactory.list(function(data) {
$scope.apps = data;
});
}]);
Full controller code : http://goo.gl/BWtiU5
Project hosted here : https://github.com/budhrg/atlantis-dashboard
Also, navigating back to Atlantis UI(dashboard) doesn't reset data like
$scope.envs, $scope.deps, $scope.envBtnText and $scope.appBtnText.
What might be issue here? Am I missing anything?
Nested States & Views
When the application is in a particular state—when a state is "active"—all of its ancestor states are implicitly active as well. Below, when the "contacts.list" state is active, the "contacts" state is implicitly active as well, because it's the parent state to "contacts.list".
Your controller isn't getting re-instantiated (expected). There are a couple ways to handle this.
See:
How to make angular ui-router's parent state always execute controller code when state changes?

Categories