I have routing config in my main app.js.
// app.js
angular.module('myApp', ["ngRoute"])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/templates/company-list.html',
controller: 'CompanyListCtrl as companyListCtrl'
}).when(...
Although in the app.js I have a directive that renders an image as a background css element of the template's div.
/app.js
// Directives
angular.module('myApp')
.directive('backImg', function () {
return function (scope, element, attrs) {
var url = attrs.backImg;
element.css({
'background-image': 'url(' + url + ')',
'background-size': 'cover'
});
};
});
CompanyListCtrl controller dependent on an http Service that makes a call to a server and returns data. That data contains 'url' for the directive above.
//controllers.js
angular.module('myApp')
.controller('CompanyListCtrl', ['CompanyService', function (CompanyService) {
var self = this;
self.companies = [];
CompanyService.getCompanies().then(function (response) {
self.companies = response.data;
});
}]);
My 'company-list.html' template with the directive renders before async data is returned. I guess I need to use 'resolve' in the route config however, what is the dependency should be there when $htt.get call is implemented as an external service?
Use the resolve option:
resolve - {Object.=} - An optional map of
dependencies which should be injected into the controller. If any of
these dependencies are promises, the router will wait for them all to
be resolved or one to be rejected before the controller is
instantiated. If all the promises are resolved successfully, the
values of the resolved promises are injected and $routeChangeSuccess
event is fired. If any of the promises are rejected the
$routeChangeError event is fired. The map object is:
key – {string}: a name of a dependency to be injected into the
controller. factory - {string|function}: If string then it is an alias
for a service. Otherwise if function, then it is injected and the
return value is treated as the dependency. If the result is a promise,
it is resolved before its value is injected into the controller. Be
aware that ngRoute.$routeParams will still refer to the previous route
within these resolve functions. Use $route.current.params to access
the new route parameters, instead.
angular.module('myApp', ["ngRoute"])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/templates/company-list.html',
controller: 'CompanyListCtrl as companyListCtrl'
resolve: {
companies: ['CompanyService', '$route', function(CompanyService, $route) {
return CompanyService.getCompanies($route.current.params.companyId).then(function(response) {
return response.data;
}
}]
}
}).when(...
angular.module('myApp')
.controller('CompanyListCtrl', ['companies', function (companies) {
var self = this;
self.companies = companies;
}]);
Related
Hi I created a model named billerModel and a route that has a resolve with a variable of billers. Now I want to retrieve and assign this variable inside my controller but I get this billerData unknown provider error. Below are my code for the route:
app.config(["$routeProvider", "$httpProvider",'$locationProvider',function($routeProvider, $httpProvider, $locationProvider) {
$routeProvider
.when("/billers", {
templateUrl: 'admin/billers/index.html',
controller: 'billerController',
resolve: {
billerData: function(billerModel) {
return billerModel.getData();
}
}
});
Below is my code for the model
app.factory('billerModel', ['$http', '$cookies', function($http, $cookies) {
return {
getData: function() {
return $http({
method: 'GET',
url: 'billers'
});
}
}
}]);
Below is my controller code that gives me the error
app.controller('billerController', ['$scope', 'billerData',
function($scope, billerData){
$scope.billers = billerData;
}]);
I also tried to remove the ng-controller from my view but if I do this then I get an error of unknown variable
<div style="text-align: left;" ng-controller="billerController">
{{ billers }}
</div>
Below is a jsfiddle but I'm not familiar on how to use it but the basic structure is included here
https://jsfiddle.net/bd06cctd/1/
Resolve data in .when blocks is only injectable into controllers defined by the .when block. Child controllers injected by the ng-controller directive can not inject resolve data.
Also if you inject billerController in the .when block and with the ng-controller directive in the .when block template, then the controller will be instantiated twice.
The $routeProvider also makes resolve data available on the view scope on the $resolve property. Child controllers instantiated by the ng-controller directive can use that.
app.controller('childController', ['$scope',
function($scope){
$scope.billers = $scope.$resolve.billerData;
}]);
Controllers instantiated by the ng-controller directive will find the $resolve property by prototypical inheritance from the view scope.
From the Docs:
resolve - {Object.<string, Function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. 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.
-- AngularJS $routeProvider API Reference
Could you try changing:
app.factory('billerModel', ['$http', '$cookies', function($http, $cookies) {
return {
getData: function() {
return $http({
method: 'GET',
url: 'billers'
});
}
}
}]);
to
app.factory('billerModel', ['$http', '$cookies', function($http, $cookies) {
return {
getData: $http({
method: 'GET',
url: 'billers'
});
}
}]);
You're returning an anonymous function, not a Promise
I have a Utils Service which is very heavy. I Want to use some of the functions defined in it on a particular user action. As this service is heavy I want to instantiate it lazily(on user action).
How do I achieve this?
Service
module.service('Utils', function (dep1, dep2) {
this.method1 = function () {
// do something
}
// other methods
});
Controller
module.controller('AppCtrl', function ($scope) {
// I don't want to inject Utils as a dependency.
$scope.processUserAction = function () {
// If the service is not instantiated
// instantiate it and trigger the methods defined in it.
}
});
Markup
<div data-ng-controller="AppCtrl">
<button data-ng-click="processUserAction()"> Click Me </button>
</div>
You can use $injector service to get services anywhere: https://docs.angularjs.org/api/auto/service/$injector. Inject the $injector into your controller, and whenever you need a service use:
This worked fine for me, the service is instantiated only on the $injector call, no error thrown.
angular.module('yp.admin')
.config(['$stateProvider', '$urlRouterProvider', 'accessLevels', '$translateWtiPartialLoaderProvider',
function ($stateProvider, $urlRouterProvider, accessLevels, $translateWtiPartialLoaderProvider) {
$stateProvider
.state('admin.home', {
url: "/home",
access: accessLevels.admin,
views: {
content: {
templateUrl: 'admin/home/home.html',
controller: 'AdminHomeController'
}
}
});
}])
.service('UtilsService', function() {
console.log('utilsSerivce instantiated');
return {
call: function() {
console.log('Util.call called');
}
};
})
.controller('AdminHomeController', ['$scope', '$rootScope', 'UserService', '$injector',
function($scope, $rootScope, UserService, $injector) {
$injector.get('UtilsService').call();
}]);
console gives me this:
stateChangeStart from: to: admin.home
stateChangeSuccess from: to: admin.home
utilsSerivce instantiated
Util.call called
If you want to delay loading the JS you should have a look at the ocLazyLoad Module: https://github.com/ocombe/ocLazyLoad. It addresses all sorts of lazy loading use cases and yours sounds like a good fit for it.
When my app starts I load some settings from a server. Most of my controllers need this before anything useful can be done. I want to simplify the controller's code as much as possible. My attempt, which doesn't work, is something like this:
app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http, $q) {
var deferred = $q.defer();
$http.get('/api/public/settings/get').success(function(data) {
$rootScope.settings = data;
deferred.resolve();
});
return deferred.promise;
}]);
app.controller('SomeCtrl', ['$rootScope', 'settings', function($rootScope, settings) {
// Here I want settings to be available
}]);
I would like to avoid having a lot of settings.then(function() ...) everywhere.
Any ideas on how to solve this in a nice way?
$http itself return promise you don't need to bind it inside the $q this is not a good practice and considered as Anti Pattern.
Use:-
app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http) {
return $http.get('/api/public/settings/get')
}]);
app.controller('SomeCtrl', ['settings',$scope, function(settings,$scope) {
settings.then(function(result){
$scope.settings=result.data;
});
}]);
Your way can be done as :-
app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http, $q) {
var deferred = $q.defer();
$http.get('/api/public/settings/get').success(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}]);
app.controller('SomeCtrl', ['$scope', 'settings', function($scope, settings) {
settings.then(function(data){
$scope.settings=data;
})
}]);
Don't overload $rootScope if you wanted it you need to use $watch for the changes in $rootScope(Not recommended).
Somewhere you would need to "wait".
The only built-in way in Angular to completely absolve the controller from having to wait on its own for async data to be loaded is to instantiate a controller with $routeProvider's route's resolve property (or the alternative $stateProvider of ui.router). This will run controller only when all the promises are resolved, and the resolved data would be injected.
So, ng-route alternative - plunker:
$routeProvider.when("/", {
controller: "SomeCtrl",
templateUrl: "someTemplate.html",
resolve: {
settings: function(settingsSvc){
return settingsSvc.load(); // I renamed the loading function for clarity
}
});
Then, in SomeCtrl you can add settings as an injectable dependency:
.controller("SomeCtrl", function($scope, settings){
if (settings.foo) $scope.bar = "foo is on";
})
This will "wait" to load someTemplate in <div ng-view></div> until settings is resolved.
The settingsSvc should cache the promise so that it won't need to redo the HTTP request. Note, that as mentioned in another answer, there is no need for $q.defer when the API you are using (like $http) already returns a promise:
.factory("settingsSvc", function($http){
var svc = {settings: {}};
var promise = $http.get('/api/public/settings/get').success(function(data){
svc.settings = data; // optionally set the settings data here
});
svc.load = function(){
return promise;
}
return svc;
});
Another approach, if you don't like the ngRoute way, could be to have the settings service broadcast on $rootScope an event when settings were loaded, and controllers could react to it and do whatever. But that seems "heavier" than .then.
I guess the third way - plunker - would be to have an app-level controller "enabling" the rest of the app only when all the dependencies have preloaded:
.controller("AppCtrl", function($q, settingsSvc, someOtherService){
$scope.loaded = false;
$q.all([settingsSvc.load, someOtherService.prefetch]).then(function(){
$scope.loaded = true;
});
});
And in the View, toggle ng-if with loaded:
<body ng-controller="AppCtrl">
<div ng-if="!loaded">loading app...</div>
<div ng-if="loaded">
<div ng-controller="MainCtrl"></div>
<div ng-controller="MenuCtrl"></div>
</div>
</body>
Fo ui-router this is easily done with having an application root state with at least this minimum definition
$stateProvider
.state('app', {
abstract: true,
template: '<div ui-view></div>'
resolve: {
settings: function($http){
return $http.get('/api/public/settings/get')
.then(function(response) {return response.data});
}
}
})
After this you can make all application states inherit from this root state and
All controllers will be executed only after settings are loaded
All controllers will gain access to settings resolved value as possible injectable.
As mentioned above resolve also works for the original ng-route but since it does not support nesting the approach is not as useful as for ui-router.
You can manually bootstrap your application after settings are loaded.
var initInjector = angular.injector(["ng"]);
var $http = initInjector.get("$http");
var $rootScope = initInjector.get("$rootScope");
$http.get('/api/public/settings/get').success(function(data) {
$rootScope.settings = data;
angular.element(document).ready(function () {
angular.bootstrap(document, ["app"]);
});
});
In this case your whole application will run only after the settings are loaded.
See Angular bootstrap documentation for details
I try to load route only after promises are resolved
var app = angular.module("thethaoso", ["ngRoute"]);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider) {
$routeProvider
.when('/', {
resolve: {
message: function (repoService) {
return repoService.getMsg();
}
}
});
}]);
app.factory('repoService', function ($http) {
return {
getMsg: function () {
return "hihihi";
}
};
});
app.controller('teamLoadCtrl', function ($scope,message) {
$scope.message= message;
});
View:
<div ng-app='thethaoso' ng-controller='teamLoadCtrl'>
{{message}}
</div>
Always get the error Error: [$injector:unpr]http://errors.angularjs.org/1.3.7/$injector/unpr?p0=messageProvider%20%3C-%20message%20%3C-%20teamLoadCtrl
full code at http://jsfiddle.net/c0y38yp0/5/
Am I missing something ?
Thanks all.
The problem is that you have not specified a template and a controller to resolve the message object to. If you used the following syntax, it will work.
.when("/", {
templateUrl: "yourView.html",
controller: "yourController",
resolve: {
message: function(yourService){
return yourService.get();
}
}
Here is a working jsfiddle: http://jsfiddle.net/c0y38yp0/10/
You can also resolve the promise manually in your controller like so:
repoService.getMsg()
.then(function (msg) {
$scope.message = msg;
}
When the promise is resolved onto the scope as I did above, the ui will update. You can show a loading bar and use ng-hide to make the pages feel fluent while the loading occurs.
When you resolve, service have to return promise not value.
Here is example service
app.factory('repoService', function ($http, $q) {
var user = {};
var q = $q.defer();
$http.get('https://api.github.com/users/Serhioromano')
.success(function(json){
user = json;
q.resolve();
}).error(function(){
q.reject();
});
return {
promise: function() {
return q.promise;
},
get: function() {
return user;
}
};
});
The point here is that you return promise only. You handle how you save result. And then you can use this result like in get(). You know that by the time you call get() the user variable already set because promise was resolve.
Now in router.
app.controller('MainCtrl', function($scope, repoService) {
$scope.user = repoService.get();
});
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '/view.html',
controller: 'MainCtrl',
resolve: {
message: function (repoService) {
return repoService.promise();
}
}
})
.otherwise({ redirectTo: '/' });
});
You return promise by repoService.promise()
In controller repoService.get() is triggered only after that promise resolved.
So you get your data.
Another thing in your code, you used ng-controller. But that thing is not binded to router and thus it avoid if it is resolved or not. You have to delete ng-controller and use controller router controller: 'MainCtrl',.
This affect your HTML
<body ng-app="myapp">
<ng-view></ng-view>
<script type="text/ng-template" id="/view.html">
<p>Hello {{user.name}}!</p>
</script>
<body>
You have to use <ng-view> to include subtemplate there and then in sub template you can use scope of the controller.
See plunker.
There are a few things wrong with the code you posted, in contrast to the code you are attempting to draw inspiration from.
When you resolve a route with the $routeProvider, the results are applied against an element <ng-view></ngview>, not a base element <div> as you have specified. Without the <ng-view> element, there is no way for the $routeProvider to bind the correct controller to the correct html fragment. Using ng-controller instantiates a controller instance when the dom element is rendered, and does not allow passing parameters to the controller as you have tried. Thus your resolution error due to an unknown message object. Effectively, message is not available outside the $routeProvider instance.
I'm trying to write a generalized route in my application and resolve the view and controller names on the fly based on the route params.
I have the following code that works:
$stateProvider.state('default', angularAMD.route({
url: '/:module/:action?id',
templateUrl: function (params) {
var module = params.module;
var action = module + params.action.charAt(0).toUpperCase()
+ params.action.substr(1);
return 'app/views/' + module + '/' + action + 'View.html';
},
controller: 'userController',
}));
However, I'm unable to figure out a way to resolve the controller name dynamically. I tried using resolve as described here, but ui-router seems to handle resolve differently than angular-route.
Any pointers?
EDIT: I've already tried using controllerProvider but it doesn't work for me (for instance, the following code just returns a hard coded controller name to test whether it actually works):
controllerProvider: function () {
return 'userController';
}
Gives me the following error:
Error: [ng:areq] Argument 'userController' is not a function, got undefined
http://errors.angularjs.org/1.3.3/ng/areq?p0=userController&p1=not%20aNaNunction%2C%20got%20undefined
This is a link to working plunker.
solution
We need two features of the UI-Router:
resolve (to load the missing pieces of js code)
controllerProvider (see cites from documentation below)
angularAMD - main.js definition
This would be our main.js, which contains smart conversion controllerName - controllerPath:
require.config({
//baseUrl: "js/scripts",
baseUrl: "",
// alias libraries paths
paths: {
"angular": "angular",
"ui-router": "angular-ui-router",
"angularAMD": "angularAMD",
"DefaultCtrl": "Controller_Default",
"OtherCtrl": "Controller_Other",
},
shim: {
"angularAMD": ["angular"],
"ui-router": ["angular"],
},
deps: ['app']
});
controllers:
// Controller_Default.js
define(['app'], function (app) {
app.controller('DefaultCtrl', function ($scope) {
$scope.title = "from default";
});
});
// Controller_Other.js
define(['app'], function (app) {
app.controller('OtherCtrl', function ($scope) {
$scope.title = "from other";
});
});
app.js
Firstly we would need some method converting the param (e.g. id) into controller name. For our test purposes let's use this naive implementation:
var controllerNameByParams = function($stateParams)
{
// naive example of dynamic controller name mining
// from incoming state params
var controller = "OtherCtrl";
if ($stateParams.id === 1) {
controller = "DefaultCtrl";
}
return controller;
}
.state()
And that would be finally our state definition
$stateProvider
.state("default", angularAMD.route({
url: "/{id:int}",
templateProvider: function($stateParams)
{
if ($stateParams.id === 1)
{
return "<div>ONE - Hallo {{title}}</div>";
}
return "<div>TWO - Hallo {{title}}</div>";
},
resolve: {
loadController: ['$q', '$stateParams',
function ($q, $stateParams)
{
// get the controller name === here as a path to Controller_Name.js
// which is set in main.js path {}
var controllerName = controllerNameByParams($stateParams);
var deferred = $q.defer();
require([controllerName], function () { deferred.resolve(); });
return deferred.promise;
}]
},
controllerProvider: function ($stateParams)
{
// get the controller name === here as a dynamic controller Name
var controllerName = controllerNameByParams($stateParams);
return controllerName;
},
}));
Check it here, in this working example
documentation
As documented here: $stateProvider, for a state(name, stateConfig) we can use controller and controllerProvider. Some extract from documentation:
controllerProvider
...
controller (optional) stringfunction
Controller fn that should be associated with newly related scope or the name of a registered controller if passed as a string. Optionally, the ControllerAs may be declared here.
controller: "MyRegisteredController"
controller:
"MyRegisteredController as fooCtrl"}
controller: function($scope, MyService) {
$scope.data = MyService.getData(); }
controllerProvider (optional) function
Injectable provider function that returns the actual controller or string.
controllerProvider:
function(MyResolveData) {
if (MyResolveData.foo)
return "FooCtrl"
else if (MyResolveData.bar)
return "BarCtrl";
else return function($scope) {
$scope.baz = "Qux";
}
}
...
resolve
resolve (optional) object
An optional map<string, function> of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them ALL to be resolved before the controller is instantiated...
I.e. let's use controllerProvider:
... to resolve the controller name dynamically...
In case, that you managed to get here, maybe you'd like to check another similar solution with RequireJS - angular-ui-router with requirejs, lazy loading of controller