I have 2 routes that share a controller, one needs data resolved prior to the view loading, and the other does not need the resolved data.
Routing segment example:
...
when('/users', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/view.html',
resolve: {
resolvedData : ['Accounts', function(Accounts) {
return Accounts.get();
}]
}
}).
when('/users/add', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/add.html'
})
...
Controller example:
app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData',
function($scope, Helper, resolvedData) {
// this works for the first route, but fails for the second route with
// unknown "resolvedDataProvider"
console.log(resolvedData);
}]);
Is there any way I can get the resolvedData in the controller without explicitly using the resolve name as a dependency? So a check can be performed?
Using the $injector does not work. I would like to do something similar to:
if ($injector.has('resolveData')) {
var resolveData = $injector.get('resolveData');
}
However this does not work even for the route that has the resolveData set ('/users'):
app.controller('UsersCtrl', ['$scope', 'Helper', '$injector',
function($scope, Helper, $injector) {
// this does not work -> fails with the unknown "resolvedDataProvider" as well
$injector.get('resolvedData');
}]);
Can this be done in angularjs? Or should I just create a new controller?
Thank you.
Looks like I figured out another way to go. The resolved data is part of the $route. So you can access it using:
app.controller('UsersCtrl', ['$scope', '$route', 'Helper',
function($scope, $route, Helper) {
if ($route.current.locals.resolvedData) {
var resolvedData = $route.current.locals.resolvedData;
}
}]);
If the other route doesn't need it, just inject undefined on that route:
router:
when('/users', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/view.html',
resolve: {
resolvedData : ['Accounts', function(Accounts) {
return Accounts.get();
}]
}
}).
when('/users/add', {
controller: 'UsersCtrl',
templateUrl: '/partials/users/add.html',
resolve: {
resolvedData: function() {
return undefined;
}
}
})
controller:
app.controller('UsersCtrl', ['$scope', 'Helper', 'resolvedData',
function($scope, Helper, resolvedData) {
if(resolvedData){
//set some scope stuff for it
} else {
//do what you do when there is no resolvedData
}
}]);
Related
In a $stateProvider state I want to:
Load a service JS file
Resolve a service function (API call)
Pass resulting data to controller
controllers/my-controller.js
angular.module('app').
controller('MyController', ['$scope', function($scope, serviceData){
console.log(serviceData)
}]);
config.js
...
.state('main', {
url: "/",
templateUrl: 'templates/my-template.html',
controller: 'MyController',
resolve: {
dependencies: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load([
'controllers/my-controller.js'
])
}],
serviceData: ['$ocLazyLoad', '$injector', function($ocLazyLoad, $injector) {
return $ocLazyLoad.load('services/my-service.js')
.then(function(){
var $myService = $injector.get('MyService');
return $myService.GetData();
})
}]
}
})
I would expect the controller to console.log the data coming back from the API call that MyService does (not included for brevity, but that part works). Instead, I get undefined.
Any ideas?
Thanks!
I started using ocLazyload to lazy load few of my AngularJs controllers. I have used it along with the $routeProvider like this
$routeProvider.when("/login", {
templateUrl: "login.html",
resolve: {
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load('LoginCtrl.js');
}]
}
}).
and this works fine.
I have another route definition which uses resolve property to resolve few items before loading the controller.
when("/dashboard", {
templateUrl: "dashboard.html",
controller: "DashboardCtrl",
resolve: {
profileData: getProfile,
count : getCount
}
}).
Now I want to lazy load this controller too, and I tried it like this
when("/dashboard", {
templateUrl: "dashboard.html",
resolve: {
profileData: getProfile,
count : getCount,
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load(['DashboardCtrl.js']);
}]
}
}).
The page loads in this case, but the profileData and count doesn't get injected into the controller. The controller definition is as given below.
var app = angular.module('gt');
app.controller('DashboardCtrl', ['$scope', '$rootScope', 'profileData', 'count',
function($scope, $rootScope, profileData, count) {
...
}]);
On debugging, I realise that the getProfile and getCount method get's called, but it happens asynchronously and the controller also lazy loads without waiting for these methods. How do I inject and lazy load at the same time? Can I use promises to resolve this in any way?
I am using AngularJS 1.3.10 & ocLazyLoad 1.0.5 versions
getProfile function for reference
var getProfile = function($q, $http, Profile, localStorageService) {
var deferred = $q.defer();
if (!localStorageService.get("loggedInUser")) {
$http.post('/loggedin').success(function(user) {
if (user) {
localStorageService.set("loggedInUser", user.email)
Profile.get(localStorageService.get("loggedInUser"), function(profileData) {
if (profileData) {
deferred.resolve(profileData);
} else {
deferred.resolve();
}
});
} else {
deferred.reject();
}
});
} else {
Profile.get(localStorageService.get("loggedInUser"), function(profileData) {
if (profileData) {
deferred.resolve(profileData);
} else {
deferred.resolve();
}
});
}
return deferred.promise;
}
getProfile.$inject = ["$q", "$http", "Profile", "localStorageService"];
I could get this working with the following configuration of $routeProvider
when("/dashboard", {
templateUrl: "dashboard.html",
controller :"DashboardCtrl"
resolve: {
profileData: getProfile,
count : getCount,
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load(['DashboardCtrl.js']);
}]
}
}).
where DashboardCtrl is the controller defined in DashboardCtrl.js
does getProfile and getCount return a promise? I would guess this is the problem as this is required. Every object put in resolve should return a promise. see the documention
If you need your resolves to happen in a specific order, you can inject them into another resolve, like this:
when("/dashboard", {
templateUrl: "dashboard.html",
resolve: {
profileData: getProfile,
count : getCount,
loadCtrl: ['$ocLazyLoad', 'profileData', 'count', function($ocLazyLoad, profileData, count) {
return $ocLazyLoad.load(['DashboardCtrl.js']);
}]
}
}).
So I have a problem with angular ui.router, which apparently isn't passing the data from resolve to controller. I have the following state set up:
$stateProvider
.state('myState', {
url: "/myUrl",
templateUrl: "myTemplate",
controller: 'myController',
resolve: {
randomData: function($q, $sails) {
var defer = $q.defer();
$sails.get("/me")
.success(function(data) {
console.log(data) // prints out actual data
defer.resolve(data);
})
return defer.promise;
}
}
and in myController I basically have
myApp.controller('myController', [
'$scope', function ($scope, randomData) {
console.log("randomData:" + randomData)
// prints out 'randomData: undefined'
}
])
According to every doc, stackoverflow post and tutorial, this piece of code should work, but it keeps printing undefined. Does anyone have an idea why this isn't working?
You forgot to inject the data in the array notation:
myApp.controller('myController', [
'$scope', 'randomData', // <-- this one
function ($scope, randomData) {
console.log("randomData:" + randomData);
}
])
I'm starting to learn AngularJS and so far so good but I am currently stuck on a small issue about an synchronous function.
I would like the function AuthenticationSharedService.login() to be called and returned before executing the rest of the code. How can I do that?
app.js
myApp.config(['$routeProvider', '$httpProvider', 'USER_ROLES',
function ($routeProvider, $httpProvider, USER_ROLES) {
$routeProvider
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController',
access: {
authorizedRoles: [USER_ROLES.all]
}
})
.when('/error', {
templateUrl: 'views/error.html',
access: {
authorizedRoles: [USER_ROLES.all]
}
})
.otherwise({
templateUrl: 'views/main.html',
controller: 'MainController',
access: {
authorizedRoles: [USER_ROLES.user]
}
});
}])
.run(['$rootScope', '$location', 'AuthenticationSharedService', 'Session', 'USER_ROLES',
function($rootScope, $location, AuthenticationSharedService, Session, USER_ROLES) {
$rootScope.$on('$routeChangeStart', function (event, next) {
<!-- Bit of code to execute before going further -->
if (!Session.login) {
console.log('First attempt to login');
AuthenticationSharedService.login();
}
<!-- /////////////////////////////////////////// -->
if (AuthenticationSharedService.isAuthenticated()) {
// user is not allowed
$rootScope.$broadcast("event:auth-notAuthorized");
} else {
// user is not logged in
$rootScope.$broadcast("event:auth-loginRequired");
}
});
}]);
authenticationSharedService.js
myApp.factory('AuthenticationSharedService', ['$rootScope', '$http', '$cookieStore', 'authService', 'Session', 'Account',
function ($rootScope, $http, $cookieStore, authService, Session, Account) {
return {
login: function () {
return Account.get(function(data) {
Session.create(data.login, data.roles);
authService.loginConfirmed(data);
});
}
};
}]);
You need to use resolve. See http://docs.angularjs.org/api/ngRoute/provider/$routeProvider or http://www.bfcamara.com/post/66001429506/authentication-in-a-spa-with-angular - this second link is quite good.
Resolve is a map of dependencies that should be injected into the controller. If any of the mapped objects are functions, the functions will be evaluated and their return values injected. If a function returns a promises, the view will not be rendered until the promise is resolved.
Just FYI, the view will not be rendered at all if the promise is rejected. You would want to deal with that situation in $rootScope.$on('routeChangeError', functionToHandleRejection)
Here's an example that should work for you:
.when('someUrl', {
resolve: {
object: function(AuthenticationSharedService) {
return AuthenticationSharedService.login();
}
}
})
I'd like to display my template when the data coming from my server are loaded.
I created a module called Services with inside some services to load my data, I'm using HomeService for my example.
var app = angular.module('MyApp', ['Services']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'home.html',
controller: 'Home_Ctrl',
resolve: {
loadData: //??
}
});
}]);
app.controller('Home_Ctrl', ['$scope', 'HomeService', function($scope, HomeService) {
$scope.data = HomeService.getData();
}
I guess I need to create a promise to do that. Is it possible to put this function inside my controller?
I mean, I don't want something like that:
var ctrl = app.controller('Home_Ctrl', ['$scope', 'HomeService', function($scope, HomeService) {
//Do something
}
//Promise
ctrl.fct = function($q) {
}
I want something like that:
app.controller('Home_Ctrl', ['$scope', '$q', 'HomeService', function($scope, $q, HomeService) {
//Do something
//Promise
this.fct = function() {}
}
Any idea?
Thanks.
You could use resolve property of controller.
You could create a object which will return promise and assign to controller resolve function and inject the same in controller definition kindly see very simple example
$routeProvider.when('/ExitPoll', {
templateUrl: '/partials/ExitPoll.html', controller: exitpollController, resolve: {
responseData: ['$http', function ($http) {
return $http.get('/Candidate/GetExitPolls/hissar').then(function (response) {
return response.data;
});
}],
}
});
var exitpollController = ['$scope', '$http','responseData','$rootScope',
function ($scope, $http, responseData, $rootScope) {
}];