My style of writing angular controllers is like this (using controller name instead of function)
angular.module('mymodule', [
])
.controller('myController', [
'$scope',
function($scope) {
// Some code here
}
]);
What I need now is when providing i routes I want to define resolve part:
$routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
resolve: myController.resolve}) // THIS IS THE CRITICAL LINE
Since controller is defined as a name how to accomplish resolve part bellow?
To clarify more in details I want to load some data from server before route is resolved and then use these data in controller.
UPDATE: To be more precise I want each module has its "resolve" function that will be called before root with that controller is executed. Solution in this post (answered by Misko Hevery) does exactly what I want but I don't have controllers as functions but as a names.
The controller definition and resolve parts are to be specified separately on the route definition.
If you define controllers on a module level you need to reference them as string, so:
$routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
controller: 'myController',
resolve: {
myVar: function(){
//code to be executed before route change goes here
};
});
The above code also shows how to define a set of variables that will be resolved before route changes. When resolved those variables can be injected to a controller so taking the example from the snippet above you would write your controller like so:
.controller('myController', ['$scope', 'myVar', function($scope, myVar) {
// myVar is already resolved and injected here
}
]);
This video might help as well: http://www.youtube.com/watch?v=P6KITGRQujQ
#pkozlowski.opensource 's answer works, but I don't really want to mess up my routing and and controllers, because I always keep it separated (from Yo Generator). Actually, we can also have controller and resolve(r) all as string/name (NOT function).
angular.module('mymodule', [
])
.controller('myController', [
'$scope', 'myModelCombination'
function($scope, myModelCombination) {
// myModelCombination[0] === (resolved) myModel
// myModelCombination[1] === (resolved) myModel2
}
])
.controller('myController2', [
'$scope', 'myModel'
function($scope, myModel) {
// Some code here
}
])
.factory('myModel', [
'$scope',
function($scope) {
// return a promise
}
])
.factory('myModel2', [
'$scope',
function($scope) {
// return a promise
}
])
.factory('myModelCombination', [
'$scope', 'myModel', 'myModel2'
function($scope) {
return $q.all(['myModel', 'myModel2']);
}
]);
Then in your routing file this should be added
$routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
resolve: ['myModel'] //ALWAYS IN ARRAY)
});
$routeProvider.when('/myModelCombination', {
templateUrl: 'partials/someroute2.html',
resolve: ['myModel'] //ALWAYS IN ARRAY)
});
http://docs.angularjs.org/api/ng.$routeProvider
This would work too
var MyController = myApp.controller('MyController', ['$scope', 'myData', function($scope, myData) {
// Some code here
}]);
MyController.resolve = {
myData: ['$http', '$q', function($http, $q) {
var defer = $q.defer();
$http.get('/foo/bar')
.success(function(data) {
defer.resolve(data);
})
.error(function(error, status) {
defer.reject(error);
});
return defer.promise;
}]
};
#TruongSinh answer worked for me and is way nicer than having additional functions in the router. I tweaked it a little as it was returning the deferred object instead of the actual resolved data.
$routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
controller: 'SomeController',
resolve: {
myModel: 'myModel'
}
});
Related
I have two controllers
angular.module('myApp.controllers', [])
.controller('Controller1',function(){
getController1();
})
.controller('Controller2',function(){
getController2();
})
I have some $http function in service with GET:
.service("geInfo", function() {
})
I want that my controllers will start only when i get the data of the service.
Do i have to use $q (promise), $watch or something else?
Does somebody can provide example?
Thanks!
You must resolve it in configuration phase:
(function() {
'use strict';
angular
.module('dashboardApp', [
'ngRoute'
])
.config(config);
/* #ngInject */
function config($routeProvider) {
$routeProvider
.when("/youUrl", {
templateUrl: "youtTemplate.html",
controller: "yourController",
resolve: {
initInfo: function(infoService){
return infoService.getInfo();
}
}
});
}
})();
Now you have initInfo in your controller:
.controller('Controller2',function($scope, initInfo){
$scope.info = initInfo;
})
By this way the router wont load the view until your service return initInfo.
I would like to know if it is possible (if it is, so how? :)), to inject a dependency to a controller called by a directive.
I have a controller controller called MyCtrl. Here is his signature:
app.controller('MyCtrl', function ($scope, dataService, aDependency){...}
This Controller is usually defined in my route:
.segment('myPage', {
templateUrl: templatesUrl + 'mypage.html',
resolve: {
aDependency: ['$q', 'dataService', '$location', function ($q, dataService, $location) {
var defer = $q.defer();
dataService.retrieveCCData(defer, $location);
return defer.promise;
}],
},
controller: 'MyCtrl'
})
But now, I would also like to call this controller from a directive.
Problem is that I don't know How to inject the aDependency.
It said that the provider is unknown.
Here's my directive:
app.directive('gettingStarted1', ['dataService', function (dataService) {
return {
restrict: 'E',
templateUrl: templatesUrl + 'mypage.html',
controller: 'MyCtrl',
//resolve: {
//datasources: ['dataService', function (dataService) {
//return null;
//}]
//}
};
}]);
Resolve is impossible in directive.
Some help will be appreciate
Thank you
Make aDependency a separate service.
app.provider('aDependency', function () {
this.$get = ['$q', 'dataService', '$location', function ($q, dataService, $location) {
var defer = $q.defer();
dataService.retrieveCCData(defer, $location);
return defer.promise;
}];
});
You can resolve it with
resolve: {
'aDependency': 'aDependency',
}
or
resolve: ['aDependency'];
you could use the controller Function from the directive
.directive("sampledirective", function (dependancy1, dependancy2, ....) {
return {
scope: '=',
controller: function ($rootScope, $scope) {
//DO your controller magic here where you got your scope stuff
}
}
})
One thing i learned it seems the $scope values arent immediatly updated from directive to Controller. If you use objects like
$scope.smth.smth = 'test'
It gets updated immediatly else you would need to $apply
What I'm trying to do is:
Make an api call as soon as the application runs (using ui-router and idea from http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/)
Store the data 'globally' so that my other controllers can have access to the data
Once the api call is done and all the controllers have resolved, show the UI (I don't want any flash of loaded content)
I know I could create an angular service to make those api calls within each controller, but if I have 2 controllers on the page, I don't want to make 2 of the same requests.
In the example below, I have a nav.controller.js that needs access to myData.
home.config.js
angular.module('myApp')
.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateProvider: function($templateCache) {
return $templateCache.get('home.client.view.html');
},
resolve: {
myService: 'myApiService',
myData: function(myApiService){
return myService.get().$promise;
}
},
controller: 'HomeCtrl as home'
});
}
]);
home.controller.js
angular.module('myApp')
.controller('HomeCtrl', ['myData',
function(myData){
var self = this;
// YAY WORKS!
console.log(myData);
}
]);
nav.controller.js
angular.module('myData')
.controller('NavCtrl', ['$scope', 'myData',
function($scope, myData) {
// BOO DOESN'T WORK
console.log(myData);
}
]);
another.controller.js
angular.module('anotherModule')
.controller('AnotherCtrl', ['$scope', 'myData',
function($scope, myData) {
// BOO DOESN'T WORK
console.log(myData);
}
]);
You should still use a service. However, this service shouldn't just make the API call - it should also store the data. Your code will look something like
home.controller.js
angular.module('myApp')
.controller('HomeCtrl', ['myService',
function(myService){
var self = this;
// YAY WORKS!
console.log(myService.myData);
}
]);
nav.controller.js
angular.module('myData')
.controller('NavCtrl', ['$scope', 'myService',
function($scope, myService) {
// BOO DOESN'T WORK
console.log(myService.myData);
}
]);
another.controller.js
angular.module('anotherModule')
.controller('AnotherCtrl', ['$scope', 'myService',
function($scope, myService) {
// BOO DOESN'T WORK
console.log(myService.myData);
}
]);
And inside your myService.get() function you store the returned data in myData
I understand how to use Restangular in a controller, however my thoughts are that Restangular is essentially an ORM on steroids.
The ORM shouldn't have any knowledge of the state of the application. That is the job of the controller.
I also want to re-use queries to the ORM, and as such, I believe that Restangular should be used inside a service.
My problem is that I am a js / angularjs and restangular noob, having only about 2-3 months exp with anything front-end.
My Controllers:
app.controller('AdminSupplierIndexController',
['$scope', '$stateParams', '$state', 'Supplier',
function ($scope, $stateParams, $state, Supplier) {
$state.reload();
Supplier.getAll.then(function (suppliers) {
$scope.suppliers = suppliers;
});
}]);
app.controller('AdminSupplierDetailController',
['$scope', '$stateParams', 'Supplier',
function ($scope, $stateParams, Supplier) {
Supplier.getOne({ supplierId : $stateParams.supplierID}).then(function(supplier) {
$scope.supplier = supplier;
});
}]);
My Factory
app.factory('Supplier', ['Restangular', function (Restangular) {
return {
getAll: Restangular.all('supplier').getList(),
getOne: Restangular.one('supplier', supplierId).get()
};
}]);
My Supplier.getAll method works fine - I can list all the suppliers from the Supplier factory.
My problem is with my Supplier.getOne method.
Question 1: How do I inject the supplierId into the factory? I am getting ReferenceError: supplierId is not defined
Question 2: Am I trying to over-engineer things considering that I would have to create individual methods for C-R-U-D for every single factory when these methods are already provided by Restangular?
I know this is old, but an alternate way would just be to wrap it within a function. This way, you can keep any other logic within the service/method.
app.factory('Supplier', ['Restangular', function (Restangular) {
return {
getAll: Restangular.all('supplier').getList(),
getOne: function(supplierId) {
return Restangular.one('supplier', supplierId).get()
}
};
}]);
Found the solution in https://github.com/mgonto/restangular#decoupled-restangular-service
Essentially, the way I have solved this problem is as follows:
app.js
$stateProvider
...
.state('admin.supplier', {
url : "/supplier",
templateUrl : 'templates/admin/supplier/index.html',
controller: "AdminSupplierIndexController",
resolve: {
suppliers: ['Supplier', function(Supplier) {
return Supplier.getList();
}]
}
})
.state('admin.supplier.detail', {
url : "/:supplierId",
templateUrl : "templates/admin/supplier/detail.html",
controller: "AdminSupplierDetailController",
resolve: {
supplier : ['Supplier', '$stateParams', function(Supplier, $stateParams) {
return Supplier.one($stateParams.supplierId).get();
}]
}
})
...
Supplier.js
app.factory('Supplier', ['Restangular', function(Restangular) {
return Restangular.service('supplier');
}]);
SupplierControllers.js
app.controller('AdminSupplierIndexController', ['$scope', '$stateParams', '$state', 'suppliers',
function ($scope, $stateParams, $state, suppliers) {
$state.reload();
$scope.suppliers = suppliers;
}]);
app.controller('AdminSupplierDetailController', ['$scope', 'supplier',
function ($scope, supplier) {
$scope.supplier = supplier;
}]);
I am trying to do an asynchronous http request to load some data before my app loads and so I am using a resolve in $routeProvider which is an http request in my MainController. For some reason, I keep getting Error: [$injector:unpr] Unknown provider: appDataProvider <- appData where appData is where I do my http request. I am using AngularJS v 1.2.5.
Here is the code and two methods that I tried that both give the same error:
Method #1
MainController.js
var MainController = ['$scope','$location','appData',
function($scope, $location, appData){
console.log(appData.data);
}
];
MainController.loadData = {
appData: function($http, $location, MainFactory){
var aid = MainFactory.extractAid($location);
return $http({method: 'GET', url: URL_CONST + aid});
}
};
app.js
var app = angular.module('HAY', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/pages/alerts'
})
.when('/pages/:pageName', {
templateUrl: function(params) {
return 'views/pages/' + params.pageName + '.html';
},
controller: MainController,
resolve: MainController.loadData
})
.otherwise({
redirectTo: '/pages/alerts'
});
});
I tried changing the name in case it was a conflicting system reserved keyword but with no luck. For some reason, appData is never recognized
Method #2
I also tried changing it around like so:
app.js
var app = angular.module('HEY', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/pages/alerts'
})
.when('/pages/:pageName', {
templateUrl: function(params) {
return 'views/pages/' + params.pageName + '.html';
},
controller: MainController,
resolve: {
appData: ['$http', '$location','MainFactory', function($http, $location, MainFactory) {
var aid = MainFactory.extractAid($location);
return $http({method: 'GET', url: URL_CONST + aid});
}]
}
})
.otherwise({
redirectTo: '/pages/alerts'
});
});
MainController.js
var MainController = ['$scope','$location','appData',
function($scope, $location, appData){
console.log(resolvedData);
}
];
However, the result was exactly the same. Does this have something to do with angular 1.2.5 ?
Here is a working version from someone else
http://mhevery.github.io/angular-phonecat/app/#/phones
And here is the code:
function PhoneListCtrl($scope, phones) {
$scope.phones = phones;
$scope.orderProp = 'age';
}
PhoneListCtrl.resolve = {
phones: function(Phone) {
return Phone.query();
},
delay: function($q, $defer) {
var delay = $q.defer();
$defer(delay.resolve, 1000);
return delay.promise;
}
}
angular.module('phonecat', ['phonecatFilters', 'phonecatServices', 'phonecatDirectives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/phones', {templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl, resolve: PhoneListCtrl.resolve}).
otherwise({redirectTo: '/phones'});
}]);
Here's an example of the code I've used in the application I'm working on, not sure it will help much because its not much different than how you have it already.
Routing
.when('/view/proposal/:id',{
controller : 'viewProposalCtrl',
templateURL : 'tmpls/get/proposal/view',
resolve : viewProposalCtrl.resolveViewProposal
})
Controller
var viewProposalCtrl = angular.module('proposal.controllers')
.controller('viewProposalCtrl',['$scope','contacts','details','rationale',
function($scope,contacts,details,rationale){
$scope.contacts = contacts;
$scope.details = details;
$scope.rationale = rationale;
// [ REST OF CONTROLLER CODE ]
});
// proposalSrv is a factory service
viewProposalCtrl.resolveViewProposal = {
contacts : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Contacts',$route.current.params.id)
.then(function(data){
return data.data.contacts;
},function(){
return [];
});
}],
details : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Details',$route.current.params.id)
.then(function(data){
return data.data.details;
},function(){
return {};
});
}],
rationale : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Rationale',$route.current.params.id)
.then(function(data){
return data.data.rationale;
},function(){
return {};
]
}]
};
Now that I think about it, when I was developing my application I did have a problem and not sure why when I named my resolve function "resolve." This gave me a problem:
.when('/path',{
// stuff here
resolve : myCtrlr.resolve
})
but this did not:
.when('/path',{
//stuff here
resolve : myCtrlr.myResolveFn
})
Another Possibility
The only other thing I can think of, is that you're returning the promise from the $http call and then trying to use appData.data Try using the .then function or one of the other functions (.success,.error) to retrieve the information from the promise.
The problem was NOT due to previously using different version of AngularJS.
Here are the fixes using the code that I have above.
In app.js, you need to declare the controller as controller: 'MainController' and NOT as controller: MainController even though you have var MainController = app.controller('MainController', ....).
Second and biggest thing was that in my index.html I declared my controller already like so:
index.html
body ng-app="HEY" controller="MainController" /body
This was causing the whole Unknown provider error Apparently angular wont tell you that you have already declared the controller that you are using to do the resolve it and that that will cause a weird error that have nothing to do with the resolve.
I hope this helps someone who may have the same problem.
One thing I noticed in angular 1x docs is that YOU DO NOT SPECIFY THE RESOLVED PARAMETER AS AN ANNOTATED DEPENDENCY
So this:
.when('/somewhere', {
template: '<some-component></some-component>',
resolve: {
resolvedFromRouter: () => someService.fetch()
}
})
export default [
'$scope',
'someService',
'resolvedFromRouter'
Controller
]
function Controller($scope, someService, resolvedFromRouter) {
// <= unknown provider "resolvedFromRouter"
}
is wrong. You don't specify the resolved parameter as a dependency, in the docs:
For easier access to the resolved dependencies from the template, the resolve map will be available on the scope of the route, under $resolve (by default) or a custom name specified by the resolveAs property (see below). This can be particularly useful, when working with components as route templates.
So just do this instead:
.when('/somewhere', {
template: '<some-component></some-component>',
resolve: {
resolvedFromRouter: () => someService.fetch()
}
})
export default [
'$scope',
'someService',
Controller
]
function Controller($scope, someService) {
$scope.$resolve.resolvedFromRouter; // <= injected here
}