Angular custom data to state objects - javascript

I'm following this sample on adding custom data to state objects but can't figure out what I'm doing wrong.
The idea is to have a Users state with a template that have 3 views: header, content and footer. The header-view gets updated with the child state's title and breadcrumb. The unnamed content-view will show the child's template (like a users list) and the footer will show summary data.
I have 2 issues:
My custom data object on my header's current state is undefined. ['Cannot read property 'title' of undefined]
If I exclude the custom data and just set the $scope values directly in the controller, it works fine but now get a 404 error. [GET http://localhost:3000/users 404 (Not Found)]. This makes no sense to me.
Am I on the right track with what I want to do? I'm unsure if I need the custom data or can I just set it in the controller?
angular.module('users').config(['$stateProvider',
function($stateProvider) {
// Users state routing
$stateProvider
.state('users', {
onEnter: function(){
console.log('state change to users');
},
abstract: true,
url: '/users',
views: {
'': {
templateUrl: 'modules/users/views/users.html'
},
'header#users': {
templateUrl: 'modules/core/views/page-header.html',
// data: { //<- this is undefined in the controller
// title: 'Users',
// breadcrumb: 'Home / Users'
// },
controller: function($scope, $state) {
$scope.title = 'Users'; //$state.current.data.title;
$scope.breadcrumb = 'Home / Users'; //$state.current.data.breadcrumb;
}
},
'footer#users': {
templateUrl: 'modules/core/views/page-footer.html'
}
}
})
.state('users.list', {
onEnter: function(){
console.log('state change to users.list');
},
url: '',
templateUrl: 'modules/users/views/users-list.html'
})
.state('signin', {
url: '/signin',
templateUrl: 'modules/users/views/authentication/signin.client.view.html'
});
}
]);
<section>
<div ui-view="header"></div>
<div ui-view=""></div>
<div ui-view="footer"></div>
</section>

You're receiving undefined because you're trying to access a data object belonging to the state itself, rather than the view you've defined it on. Typically, data would be defined against the state, but if you wish to do so against the view, you will need to use:
views: {
'header#users': {
data: {
title: 'Users',
},
controller: function($scope, $state) {
$scope.title = $state.current.views['header#users'].data.title;
}
}
}
As for your 404 error, there is nothing presented in the code that would cause this, so the problem must lay elsewhere.

Related

Sub view for $state not rendering in named ui-view

https://plnkr.co/edit/VV13ty8XaQ20tdqibmFy?p=preview
Expected
After login the dashboard state renders dashboard.html, and all components and ui-views should render: tickers, tags, social(named ui-view) and feed.
Results
After login the dashboard state renders dashboard.html however only the components tickers,tags and feed show up, but not the social (named-ui-view)
I feel that my problem lies somewhere around where I transition from the login state to the dashboard state. Once you hit the dashboard state, it serves up the default template which is the component element tag: <dash-module></dash-module>. This will then render the dash.component template: dashboard.html and controller. However I've lost access to the social view in the dashboard state object.
dashboard.html
<div class="jumbotron text-center">
<h1>The Dashboard</h1>
</div>
<div class="row">
<tickers-module></tickers-module>
<tags-module></tags-module>
// Expecting the social-module-template.html to show below:
<div ui-view="social"></div>
<feed-module></feed-module>
</div>
The routerApp module with the dashboard component full code in Plnkr
// RouterApp module
////////////////////////////////////////////////////////////////////////////////
var routerApp = angular.module('routerApp', ['ui.router', 'tickers', 'tags', 'feed']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
const login = {
name: 'login',
url: '/login',
templateUrl: 'login.html',
bindToController: true,
controllerAs: 'l',
controller: function($state) {
this.login = function() {
$state.go('dashboard', {});
}
}
}
const dashboard = {
name: 'dashboard',
url: '/dashboard',
params: {
ticker: {},
tags: {}
},
template: '<dash-module></dash-module>',
views: {
'' : {
templateUrl: 'dashboard.html',
},
'social' : {
templateUrl: 'social-module-template.html',
controller: function($state) {
console.log('Social init', $state.params);
}
}
}
}
$stateProvider
.state(login)
.state(dashboard);
})
tags.component('dashModule', {
templateUrl: 'dashboard.html',
controller: function($scope, $state) {
console.log('dashModule loaded!');
}
})
This is the part that should render the social html content in the <div ui-view="social"></div>
views: {
'' : {
templateUrl: 'dashboard.html',
},
'social' : {
templateUrl: 'social-module-template.html',
controller: function($state) {
console.log('Social init', $state.params);
}
}
}
I made changes to your plunker here You were missing # here.
const dashboard = {
name: 'dashboard',
url: '/dashboard',
params: {
ticker: {},
tags: {}
},
template: '<dash-module></dash-module>',
views: {
'' : {
templateUrl: 'dashboard.html',
},
'social#dashboard' : {
templateUrl: 'social-module-template.html',
controller: function($state) {
console.log('Social init', $state.params);
}
}
}
}
In order for these components to appear under the home state, we must define them using absolute naming. Specifically, we must use the # syntax to tell AngularJS that these components of our application should be mapped to a specific state. This follows the viewName#stateName syntax and tells our application to utilize named views from an absolute, or specific state. You can read more about relative vs. absolute names here.
See this for more information.
The problem you have is named view has to render in same state i.e Dashboard.
Change the following and it should work.
social#dashboard
Check this Plunkr
Named Views UI router

AngularJS - How to render template AND data from a promise

Alright, I'm pretty new to Angular, spent the last two days trying to find a good way to do this and failed. I'm not sure if the title is good either.
I'm trying to make a simple page with a menu. The person would click a menu link and then the view that's below the menu should render accordingly (without refreshing the whole page of course). Sounds easy.
But the thing is, there's going to be a menu for admins and a menu for regular users, so the menu is loaded through ajax. This is an example of what I get:
[
{
name: "Manage games",
templateUrl: "/view/mygames.html",
url: "/games",
},
{
name: "Weekly Reports",
templateUrl: "/view/myreports.html",
url: "/reports"
},
{
name: "Manage Users",
templateUrl: "/view/users.html",
url: "/users",
adminRequired: true
}
];
After the menu is loaded, when a menu element is clicked, I want to get data making an ajax call to the url property, and the template to fetch this data to will also be an ajax call to the templateUrl property.
So, how is that achievable? Basically what I want is to have a directive/component/whatever, that by default will be empty, not displayed or rendered. But when I click on a element from the menu, I'm going to $broadcast an event with the dataUrl/templateUrl to the directive/component/whatever, and it will make two ajax calls, one two get the data, and another to get the template, after both get done, it will render and appear on the page.
Any way to this, or suggestion to do something similar to this would be greatly appreciated
By the way, I'm using Angular 1.5.7
You should use routing (in my example it's the ui-router) for achieving this.
The ui-router has a resolve property that lets you resolve controller dependencies and lets you then inject them into your controller for using them.
Here's a full example that I've made (sorry for the poor ui):
HTML:
<div ng-app="app">
<div ng-controller="homeCtrl as vm">
<menu items="vm.items"></menu>
</div>
<div>
<ui-view></ui-view>
</div>
</div>
JS:
var app = angular.module('app', ['ui.router']);
app.controller('gamesCtrl', function(data) {
this.title = data.title;
}).
controller('reportsCtrl', function(data) {
this.title = data.title;
}).
controller('usersCtrl', function(data, adminData) {
this.title = data.title;
this.removedUsers = adminData.removedUsers;
}).
controller('homeCtrl', function() {
this.items = [{
name: 'Manage games',
state: 'games'
}, {
name: 'Weekly Reports',
state: 'reports'
}, {
name: 'Manage Users',
state: 'users',
adminRequired: true
}];
});
app.component('menu', {
bindings: {
items: "="
},
template: '<div ng-repeat="item in $ctrl.items"><span ng-click="$ctrl.goToState(item)">{{item.name}}</span></div>',
controller: function($state) {
this.goToState = function(item) {
console.log('redirecting to state:' + item.state);
$state.go(item.state);
}
}
});
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.
state('games', {
url: '/games',
template: '<div><h1>{{vm.title}}</h1></div>', // use templateUrl..
resolve: {
data: function($q) {
return $q.when({
title: 'games'
})
}
}, // return injectables who return promises and inject them into your ctrl
controller: 'gamesCtrl as vm'
}).
state('reports', {
url: '/reports',
template: '<div><h1>{{vm.title}}</h1></div>', // use templateUrl..
resolve: {
data: function($q) {
return $q.when({
title: 'reports'
})
}
}, // return injectables who return promises and inject them into your ctrl
controller: 'reportsCtrl as vm'
}).
state('users', {
url: '/users',
template: '<div><h1>{{vm.title}}</h1><div>Removed Users:</div><div ng-repeat="user in vm.removedUsers">{{user}}</div></div>', // use templateUrl..
// return injectables who return promises and inject them into your ctrl
resolve: {
data: function($q) {
return $q.when({
title: 'users'
})
},
adminData: function($q) {
return $q.when({
removedUsers: ['user1', 'user2', 'user3']
})
}
},
controller: 'usersCtrl as vm'
}).
state('default', {
url: '/default',
template: '<h1>This is the default state</h1>'
});
$urlRouterProvider.otherwise('/default');
});
JSFIDDLE.
Remarks:
You should use templateUrl instead of template when configurating the states.
I've used $q.when to demonstrate a return of a promise. You will probally use $http.get\post instead.

AngularJS (Ionic Framework) - changing State within controller doesn't seem to be working

What I am trying to do is within the Search controller, once I get the search results back from the server ($http) change view to a different view - the search results view. I am not sure if the approach I am going about it is right, but either-way it doesn't seem to be working. I will need to pass the response as well, so the new view can display the results/response.
My app.js:
.....state('tab.search', {
url: '/search',
views: {
'tab-search': {
templateUrl: 'templates/tab-search.html',
controller: 'SearchCtrl as search'
}
}
})
.state('tab.search-results', {
url: '/results',
views: {
'tab-search-results': {
templateUrl: 'templates/tab-search-results.html',
controller: 'SearchResultsCtrl as searchResults'
}
}
})
Then my search controller has:
.controller('SearchCtrl', function($scope, $state, $location, $ionicPopup, service) {
....
$scope.doSearch = function(state) {
.....
var result = service.doSearch(dataObj);
result.then(function(response) {
console.log("I'm here");
$state.go('tab.search-results');
......
My search results view (tab-search-results.html) has the following basic code at the moment:
<ion-view view-title="Search Results">
<ion-content padding="true">
hello world
</ion-content>
</ion-view>
This basic structure is how all my other pages/views are setup too.
What happens when I perform the search is that the console message gets outputted, and then the URL changes to /results as per the tab.search-results state, but the template/view doesn't change/show.
Interestingly if I change $state.go('tab.search-results'); to point to another app state/view that I know works, it works perfectly - but for whatever reason this state/view isn't working.
Also, if there is a better way of achieving this same thing, then please let me know. I will be needing to eventually pass the "response" from SearchCtrl to SearchResultsCtrl - or rather access it on the search results page in one form or another.
Many thanks.
I think you are looking for $stateParams.
var result = service.doSearch(dataObj);
result.then(function(response) {
$state.go('tab.search-results', {'searchData':response});
}
In your routes file:
.state('tab.search-results', {
url: '/results/:searchData',
views: {
'tab-search-results': {
templateUrl: 'templates/tab-search-results.html',
controller: 'SearchResultsCtrl as searchResults'
}
}
})
And in your SearchResultsCtrl:
.controller($stateParams) {
console.log($stateParams.searchData) // will give you search results
}
NOTE:If you don't want to pass data through the URL you can use params key in the .state() method.
.state('tab.search-results', {
url: '/results',
params: {
'searchData':null
},
views: {
'tab-search-results': {
templateUrl: 'templates/tab-search-results.html',
controller: 'SearchResultsCtrl as searchResults'
}
}
})
I realised why my view wasn't changing properly. The fix was changing the views in the sub-view to reference the parent view.
Fail (sub-view has unique name from parent):
.....state('tab.search', {
url: '/search',
views: {
'tab-search': {
templateUrl: 'templates/tab-search.html',
controller: 'SearchCtrl as search'
}
}
})
.state('tab.search-results', {
url: '/results',
views: {
'tab-search-results': {
templateUrl: 'templates/tab-search-results.html',
controller: 'SearchResultsCtrl as searchResults'
}
}
})
Success (sub-view references parent, 'tab-search'):
.....state('tab.search', {
url: '/search',
views: {
'tab-search': {
templateUrl: 'templates/tab-search.html',
controller: 'SearchCtrl as search'
}
}
})
.state('tab.search-results', {
url: '/results',
views: {
'tab-search': {
templateUrl: 'templates/tab-search-results.html',
controller: 'SearchResultsCtrl as searchResults'
}
}
})
Thanks all, I think I worked out the problem. It was putting the search results page under the tab abstract state. eg: tab.search-results rather than search-results - I am guessing this was the problem as there is no search results tab. When I re-named the state to just search-results (and modified the $state.go to use 'search-results' instead of 'tab.search-results') it worked. Does this seem right?

AngularJS - Loading named views within child states ( not abstract )

Alright so I am having an issue with my named views loading content into my state.
Its mostly problematic because I really do not know why it isnt working; with angular that usually means a typo but I have recreated my problem in a plunker and am getting the same results so maybe I am missing something.
I know this question has been asked before:: however in all the results I saw on here people were putting content into an abstract state's children. what I want to do is have a state; populate it with named views as well as other content relevant to that state; then have that states children load content into the main states named views. should be simple enough and rather straight forward but alas mine will not work for me.
Here is the link to the plunker made:: http://plnkr.co/edit/TWCQuoIyJRvTb42Z7xxe?p=preview
as you will see the main 'papers' state is loading. however none of the content from the named views is being loaded into the 'papers' state from its child state 'papers.views'.
Code for reference:
Module declaration and state config(app.js)
var app = angular.module( 'app', [ 'ui.router' ] );
app.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/papers');
// States
$stateProvider
.state( 'papers', {
url: "/papers",
templateUrl: 'papers.html'
}) // nested paper state + views
.state( 'papers.views', {
views: {
'#papers': {
templateUrl: 'papers.home.html'
},
'paper1#papers': {
templateUrl: 'papers.paper1.html'
},
'paper2#papers': {
templateUrl: 'papers.paper2.html'
}
}
})
}
])
.run(['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}])
Index page (papers.html loading here):
<body>
<div ui-view></div>
</body>
papers page ( where nested views are supposed to be loading )
<h1>This is the papers page. other views should load in here</h1>
<div ui-view ></div>
<div ui-view="paper1" ></div>
<div ui-view="paper2" ></div>
One way, how to fix this is to add two lines:
change your parent to be abstract : true and
force child to define url : ''
There is an upated and working plunker, this is the updated state def:
$urlRouterProvider.otherwise('/papers');
// States
$stateProvider
.state( 'papers', {
// NEW LINE
abstract: true,
url: "/papers",
templateUrl: 'papers.html'
}) // nested paper state + views
.state( 'papers.views', {
// NEW LINE - because parent is abstract, same url here - this will be loaded
url: '',
views: {
'#papers': {
templateUrl: 'papers.home.html'
},
'paper1#papers': {
templateUrl: 'papers.paper1.html'
},
'paper2#papers': {
templateUrl: 'papers.paper2.html'
}
}
})
More details about this in documentation:
How to: Set up a default/index child state
Check it here
Another way could be to change the default:
$urlRouterProvider.otherwise('/papers/view');
And add url: '/view' to child state:
...
.state( 'papers.views', {
url: '/view',
views: {
...
Check this version here

How to reload a child view without reloading whole state in AngularJS

I have a state that has multiple views declared in it as follows:
$stateProvider
.state('home.details.item', {
url: '^/details',
views: {
'chartsView': {
templateUrl: 'charts.html',
controller: 'chartsCtrl'
},
'gridView': {
templateUrl: 'grid.html',
controller: 'gridCtrl'
},
'detailsView': {
templateUrl: 'details.html',
controller: 'detailsCtrl'
}
}
});
I need to reload one of the views without reloading the whole state, without using $state.go($state.current,null , {reload: true}) , and if possible, from the chartCtrl reload detailsCtrl. Is that possible?
I'd say, that the UI-Router solution should be built arround *states*, not views.
(I created working example here). Other words, if there are
some views which should not be reloaded and
some other views, which should be reloaded
... it calls for state nesting. Let's move that view into child state:
.state('home.details.item', {
url: '^/details',
views: {
'chartsView': {
templateUrl: 'tpl.charts.html',
controller: 'chartsCtrl'
},
'gridView': {
templateUrl: 'tpl.grid.html',
controller: 'gridCtrl'
},
// 'detailsView': {
// templateUrl: 'details.html',
// controller: 'detailsCtrl'
// }
}
})
.state('home.details.item.more', {
views: {
'detailsView#home.details': {
templateUrl: 'tpl.details.html',
controller: 'detailsCtrl'
}
}
})
We also need a state, which will do the reload. We could use other way, e.g. with some changing parameter in state more, but that would mean to change the param value on each call. With this specil state, we can easily reload our state 'more':
.state('reload', {
parent: "home.details.item",
views: {
'detailsView#home.details': {
// this controller will just redirect to 'more' and make it fresh...
controller: ['$state', function($state) { $state.go('^.more')}],
}
}
})
And with these simple controllers we can do all that required stuff:
.controller('chartsCtrl', function ($scope, $state) {
var childName = ".more";
$state.go(childName); // default is a sub state 'more'
})
.controller('detailsCtrl', function ($scope) {
$scope.when = Date.now();
})
Having this: we can call this to reload just details:
<a ui-sref="reload">force reload detail view</a>
Now, when navigating to reload, we will be redirected to state "more" and our view will be rerendered.
SUMMARY:
In general, UI-Router represents state machine. I would strongly suggest:
Do not worry to think in states. Views are just their representation in the DOM.
If there are some features related, they most likely represent state. If others do not relate (should be changed often or rarely) they belong to other state. It could be parent, child or sibling...
Check it here

Categories

Resources