Child state controller is never executed - javascript

I was trying to wrap my head around ui-router and I've tried to implement the following logic:
if there is no state, go to state /items
when processing /items, retrieve a list of "items" from the server
when "items" are received go to state /items/:item, where "item" is the first in the list of items, returned by the server
in state /items/:item render a list of items with the corresponding "item" being "highlighted" (the highlighting part is not included in my code)
However, the child state's "controller" function is not executed. I bet it's something really obvious.
Here's the js (I also have it on plunkr with the accompanying templates).
angular.module('uiproblem', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/items');
$stateProvider
.state('items', {
url: '/items',
resolve: {
items: function($q, $timeout){
var deferred = $q.defer();
$timeout(function() {
deferred.resolve([5, 3, 6]);
}, 1000);
return deferred.promise;
}
},
controller: function($state, items) {
// We get to this point successfully
console.log(items);
if (items.length) {
// Attempt to transfer to child state
return $state.go('items.current', {id: items[0]});
}
}
})
.state('items.current', {
url: '/:id',
templateUrl: 'item.html',
controller: function($scope, items) {
// This is never reached, but the I can see the partial being
// loaded.
console.log(items);
// I expect "items" to reflect to value, to which the "items"
// promise resolved during processing of parent state.
$scope.items = items;
}
});
}]);
Plunk: http://plnkr.co/edit/K2uiRKFqe2u5kbtTKTOH

Add this to your items state:
template: "<ui-view></ui-view>",
States in UI-Router are hierarchical, and so are their views. As items.current is a child of items, so is it's template. Therefore, the child template expects to have a parent ui-view to load into.
If you prefer to have the child view replace the parent view, change the config for items.current to the following:
{
url: '/:id',
views: {
"#": {
templateUrl: 'item.html',
controller: function($scope, items) {
// ...
}
}
}
}

Related

Angular ui-router resolve inheritance

I would like to create an abstract parent state, that has only one job: to resolve the current user through an ajax server call, and then pass this object to the child state. The problem is that the child state never gets loaded. Please have a look at this plunker: Example
a state
angular.module('test', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider){
// Parent route
$stateProvider.state('main', {
abstract:true,
resolve: {
user: function(UserService){
return UserService.getUser();
}
}
});
// Child route
$stateProvider.state('home', {
parent: 'main',
url: '/',
controller: 'HomeController',
controllerAs: '$ctrl',
template: '<h1>{{$ctrl.user.name}}</h1>'
});
$urlRouterProvider.otherwise('/');
});
a factory
angular.module('test').factory('UserService', function($q){
function getUser() {
var deferred = $q.defer();
// Immediately resolve it
deferred.resolve({
name: 'Anonymous'
});
return deferred.promise;
}
return {
getUser: getUser
};
});
a controller
angular.module('test').controller('HomeController', function(user){
this.user = user;
});
In this example, the home state will never display the template, I don't really understand why. If I remove the parent: 'main' line, then it displays the template, but of course I get an error because it cannot find the user dependency in the HomeController.
What am I missing? I did everything like it is described in ui-router's documentation, I think this should work.
Every parent must have a target ui-view in template for its child
$stateProvider.state('main', {
abstract:true,
resolve: {
user: function(UserService){
return UserService.getUser();
}
}
template: '<div ui-view=""></div>'
});
NOTE: Another option is to use absolute names and target index.html .. but in this case the above is the way to go (Angularjs ui-router not reaching child controller)

How can I resolve on state change into a controller on nested views

I'm trying to perform a resolve on state change to get data I want to inject in a controller which uses "multiple" views. The reason for having nested views is because the template/app.html contains a <ion-side-menu>, and I want to resolve data inside the <side-menu-content>.
CODE
module configuration:
$stateProvider.state('app', {
url: '/app',
abstract: true,
templateUrl: 'template/app.html'
})
.state('app.list', {
url: '/list',
views: {
'maincontainer#app': {
controller: 'listctrl',
templateUrl: 'template/list.html',
resolve: {
item: function(dataservice) {
return dataservice.getItems();
}
}
}
},
resolve: {
auth: auth
}
});
controller:
angular.module('controller', []).controller('listctrl',
['$scope', function($scope, items){
console.log(items); // prints undefined
}]);
PROBLEM
The problem is that the resolved items is never injected into the controller, though the item function is resolved.
I've been thinking about maybe having to store the data in local storage when resolved, and getting the items back again from the controller. I'd prefer if I didn't have to go that route (pun intended).
You have to actually inject the items.
angular.module('controller', []).controller('listctrl',
['$scope', "items", function($scope, items){
console.log(items); // prints undefined
}]);

Redirect to Child after Parent is resolved

I have a parent route which loads a list of objects in the resolve function. After the user selects a item of this list it loads the child route. The child route appends the itemId to the url. Now I would like that the parent automatically "redirects" to the first item of the list and therefore change to the child route.
I tried calling $state.go in the resolve function after the promise was resolved but that started a endless redirect cycle.
Here is my current setup.
$stateProvider.state("parent", {
url: "/parent/:parentId/children",
templateUrl: "parentTempl.html",
controller: "ParentController",
controllerAs: "vm",
resolve: {
ParentLoadingService: function ($stateParams, ResourceService) {
return ResourceService.request.getChildren({ parentId: $stateParams.parentId }).$promise;
}
}
}).state("parent.child", {
url: "/:childId",
templateUrl: "child.html",
controller: "ChildController",
controllerAs: "vm",
resolve: {
ChildLoadingService: function ($stateParams, ParentLoadingService) {
...
}
}
});
thanks

AngularJS ui-router: how to resolve typical data globally for all routes?

I have an AngularJS service which communicates with the server and returns
translations of different sections of the application:
angular
.module('utils')
.service('Translations', ['$q','$http',function($q, $http) {
translationsService = {
get: function(section) {
if (!promise) {
var q = $q.defer();
promise = $http
.get(
'/api/translations',
{
section: section
})
.success(function(data,status,headers,config) {
q.resolve(result.data);
})
.error(function(data,status,headers,config){
q.reject(status);
});
return q.promise;
}
}
};
return translationsService;
}]);
The name of the section is passed as the section parameter of the get function.
I'm using AngularJS ui-router module and following design pattern described here
So I have the following states config:
angular.module('app')
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('users', {
url: '/users',
resolve: {
translations: ['Translations',
function(Translations) {
return Translations.get('users');
}
]
},
templateUrl: '/app/users/list.html',
controller: 'usersController',
controllerAs: 'vm'
})
.state('shifts', {
url: '/shifts',
resolve: {
translations: ['Translations',
function(Translations) {
return Translations.get('shifts');
}
]
},
templateUrl: '/app/shifts/list.html',
controller: 'shiftsController',
controllerAs: 'vm'
})
This works fine but as you may notice I have to explicitly specify translations in the resolve parameter. I think that's not good enough as this duplicates the logic.
Is there any way to resolve translations globally and avoid the code duplicates. I mean some kind of middleware.
I was thinking about listening for the $stateChangeStart, then get translations specific to the new state and bind them to controllers, but I have not found the way to do it.
Any advice will be appreciated greatly.
Important note:
In my case the resolved translations object must contain the translations data, not service/factory/whatever.
Kind regards.
Let me show you my approach. There is a working plunker
Let's have a translation.json like this:
{
"home" : "trans for home",
"parent" : "trans for parent",
"parent.child" : "trans for child"
}
Now, let's introduce the super parent state root
$stateProvider
.state('root', {
abstract: true,
template: '<div ui-view=""></div>',
resolve: ['Translations'
, function(Translations){return Translations.loadAll();}]
});
This super root state is not having any url (not effecting any child url). Now, we will silently inject that into every state:
$stateProvider
.state('home', {
parent: 'root',
url: "/home",
templateUrl: 'tpl.html',
})
.state('parent', {
parent: 'root',
url: "/parent",
templateUrl: 'tpl.html',
})
As we can see, we use setting parent - and do not effect/extend the original state name.
The root state is loading the translations at one shot via new method loadAll():
.service('Translations', ['$http'
,function($http) {
translationsService = {
data : {},
loadAll : function(){
return $http
.get("translations.json")
.then(function(response){
this.data = response.data;
return this.data;
})
},
get: function(section) {
return data[section];
}
};
return translationsService;
}])
We do not need $q at all. Our super root state just resolves that once... via $http and loadAll() method. All these are now loaded, and we can even place that service into $rootScope:
.run(['$rootScope', '$state', '$stateParams', 'Translations',
function ($rootScope, $state, $stateParams, Translations) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.Translations = Translations;
}])
And we can access it anyhwere like this:
<h5>Translation</h5>
<pre>{{Translations.get($state.current.name) | json}}</pre>
Wow... that is solution profiting almost from each feature coming with UI-Router... I'd say. All loaded once. All inherited because of $rootScope and view inheritance... all available in any child state...
Check that all here.
Though this is a very old question, I'd like to post solution which I'm using now. Hope it will help somebody in the future.
After using some different approaches I came up with a beautiful angularjs pattern by John Papa
He suggest using a special service routerHelperProvider and configure states as a regular JS object. I'm not going to copy-paste the entire provider here. See the link above for details. But I'm going to show how I solved my problem by the means of that service.
Here is the part of code of that provider which takes the JS object and transforms it to the states configuration:
function configureStates(states, otherwisePath) {
states.forEach(function(state) {
$stateProvider.state(state.state, state.config);
});
I transformed it as follows:
function configureStates(states, otherwisePath) {
states.forEach(function(state) {
var resolveAlways = {
translations: ['Translations', function(Translations) {
if (state.translationCategory) {
return Translations.get(state.translationCategory);
} else {
return {};
}
}],
};
state.config.resolve =
angular.extend(state.config.resolve || {}, resolveAlways || {});
$stateProvider.state(state.state, state.config);
});
});
And my route configuration object now looks as follows:
{
state: ‘users’,
translationsCategory: ‘users’,
config: {
controller: ‘usersController’
controllerAs: ‘vm’,
url: ‘/users’.
templateUrl: ‘users.html'
}
So what I did:
I implemented the resolveAlways object which takes the custom translationsCategory property, injects the Translations service and resolves the necessary data. Now no need to do it everytime.

Is there a way to pass variables to a controller from ui.router?

I have a page structured with some nested views, using ui.router and I would like to pass some data from the parent controller to the child controller, without injecting useless services into the child controller.
In my mind, something like these would be perfect
state('home', {
url: "/home",
templateUrl: "parts/home.html",
controller: "FatherController"
}).
state('home.child', {
url: "/child",
templateUrl: "parts/home/child.html",
controller: "ChildController",
params: {$scope.data = $rootScope.someData}
})
Do you happen to know if there is a way to do this?
If your child view is nested within the parent view, your child controller will automatically inherit the parent scope.
You should be able to access the parent controller's data directly from the child controller.
Well, I guess you don't always have the choice to move the data to a parent controller or such.
My recommendation for this would be to use resolvers (https://github.com/angular-ui/ui-router/wiki#resolve) to do some magic.
Here's a sample on how it could be made to work:
var dataResolver = ['$scope', '$stateParams', 'Service',
function($scope, $stateParams, Service) {
Service.get($stateParams.objectId).then( function(obj) {
$scope.myObject = obj;
return obj;
});
};
];
$stateProvider.state("foo.details", {
"url": '/foo/:objectId',
"resolve": { "data": dataResolver },
"controller": "SomeController",
"template": "<ui-view />"
)
And you magically get the $scope.obj data when the controller is instanciated, whatever how.
You can use Query Parameters and access using $stateParams
https://github.com/angular-ui/ui-router/wiki/URL-Routing
Well, in my projects I use resolve of Angular UI router.
Basically, when initializing the parent state, It will retrieve data from the server and store it into listItem. You also can separate the logic of making request to server using a service and inject it into config.
Suppose I click somewhere in the parent state to open the new child state with an Id as a query string. Then we get this id by $stateParams and filter to find the correct item in listItem (using Underscore)
route.js
.state('parent', {
url: '/parent',
templateUrl: 'parent-template.html',
controller: 'ParentController',
resolve: {
listItem: ['$http', '$stateParams', function ($http, $stateParams) {
return $http.get({'/GetListItem'}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return [];
});
}]
}
})
.state('parent.child', {
url: '/{itemId}',
templateUrl: 'child-template.html',
controller: 'ChildController',
resolve: {
item: ['$stateParams', 'listItem', function ($stateParams, bundles) {
return _.findWhere(listItem, { Id: $stateParams.itemId });
}]
}
})
Then you can access to listItem and item in the controller like below.
parent.controller.js
(function () {
function ParentController($scope, listItem) {
}
ParentController.$inject = ['$scope', 'listItem']
angular.module('app').controller('parentController', ParentController)
})()
child.controller.js
(function () {
function ChildController($scope, item) {
}
ChildController.$inject = ['$scope', 'item']
angular.module('app').controller('childController', ChildController)
})()

Categories