I am using ui bootstrap and use tmhDynamicLocaleProvider to get the correct translations for days,month etc in my datepicker.
It works all fine as long as I load the locale documents from online. If I load documents locally (I need to do it locally), it doesn't load the correct translations after minification.
My code looks as follows
app.config(['tmhDynamicLocaleProvider', function(tmhDynamicLocaleProvider) {
tmhDynamicLocaleProvider.localeLocationPattern('app/datepickerLocale/locale.{{locale}}.js');
}])
app.config(....{
$provide.decorator('uibDatepickerDirective', ['$delegate', function($delegate) {
angular.forEach($delegate, function (directive) {
var originalCompile = directive.compile;
var originalLink = directive.link;
if (originalCompile) {
directive.compile = function () {
return function (scope) {
scope.$on('$localeChangeSuccess', function () {
scope.move(0);
});
originalLink.apply(this, arguments);
};
}
}
});
return $delegate;
}]);
})
I resolve it in a state
.state('main', {
url: '/{language:[a-z]{2}}',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl',
controllerAs: 'mainCtrl',
resolve: {
localeLanguage: ['resolveService', '$stateParams', function(resolveService, $stateParams){
resolveService.resolveLocale($stateParams)
}]
}
})
the service looks as follows
resolveLocale: function(stateParams){
var deferred = $q.defer();
if(stateParams.language){
tmhDynamicLocale.set(stateParams.language);
deferred.resolve(1);
} else {
deferred.resolve(2);
}
return deferred.promise;
}
it all works fine until minification. After that I obtain the error, that
the script was not able to be obtained. (GET error).
I assume that the while invoking the function the script locale.en.js has not been loaded yet. Or am I wrong here?
How can I solve this?
Related
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']);
}]
}
}).
I have tried everything to get ui-router's resolve to pass it's value to the given controller–AppCtrl. I am using dependency injection with $inject, and that seems to cause the issues. What am I missing?
Routing
$stateProvider.state('app.index', {
url: '/me',
templateUrl: '/includes/app/me.jade',
controller: 'AppCtrl',
controllerAs: 'vm',
resolve: {
auser: ['User', function(User) {
return User.getUser().then(function(user) {
return user;
});
}],
}
});
Controller
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope'];
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
console.log(auser); // undefined
...
}
Edit
Here's a plunk http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=preview
When you use route resolve argument as dependency injection in the controller bound to the route, you cannot use that controller with ng-controller directive because the service provider with the name aname does not exist. It is a dynamic dependency that is injected by the router when it instantiates the controller to be bound in its respective partial view.
Also remember to return $timeout in your example, because it returns a promise otherwise your argument will get resolved with no value, same is the case if you are using $http or another service that returns a promise.
i.e
resolve: {
auser: ['$timeout', function($timeout) {
return $timeout(function() {
return {name:'me'}
}, 1000);
}],
In the controller inject the resolve dependency.
appControllers.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$rootScope','auser']; //Inject auser here
function AppCtrl($scope, $rootScope, auser) {
var vm = this;
vm.user = auser;
}
in the view instead of ng-controller, use ui-view directive:
<div ui-view></div>
Demo
Here is how I work with resolve. It should receive promise. So I create service accordingly.
app.factory('User', function($http){
var user = {};
return {
resolve: function() {
return $http.get('api/user/1').success(function(data){
user = data;
});
},
get: function() {
return user;
}
}
});
This is main idea. You can also do something like this with $q
app.factory('User', function($q, $http){
var user = {};
var defer = $q.defer();
$http.get('api/user/1').success(function(data){
user = data;
defer.resolve();
}).error(function(){
defer.reject();
});
return {
resolve: function() {
return defer.promise;
},
get: function() {
return user;
}
}
});
These are almost identical in action. The difference is that in first case, service will start fetching date when you call resolve() method of service and in second example it will start fetch when factory object is created.
Now in your state.
$stateProvider.state('app.index', {
url: '/me',
templateUrl: '/includes/app/me.jade',
controller: function ($scope, $rootScope, User) {
$scope.user = User.get();
console.log($scope.user);
},
controllerAs: 'vm',
resolve: {
auser: function(User) {
return User.resolve()
}
}
});
The problem here is I am able to access the getRoutes(), but I am unable to access the injected constant -"configuration". What am I missing? Thanks.
(function () {
'use strict';
var app = angular.module('app');
app.constant('configuration', {
PARTIAL_PATH: "/app/components/partials"
});
app.module('app', [
'routeService'
]);
var routeServiceModule = angular.module('routeService', ['common']);
routeServiceModule.provider('routeConfig',function () {
this.getRoutes = function () {
return [
{
url: '/login',
config: {
title: 'admin',
templateUrl: 'app/components/login/login.html'
}
}, {
url: '/',
config: {
templateUrl: 'app/components/dashboard/dashboard.html',
title: 'Dashboard'
}
}
];
};
this.$get = ['configuration', function (configuration) {
var service = {
getRoutes: getRoutes(),
configuration: configuration.PARTIAL_PATH
};
return service;
}];
app.config(['$routeProvider', 'routeConfigProvider', function ($routeProvider, routeConfigProvider) {
//Unable to get the configuration value
console.log(routeConfigProvider.configuration);
//Console is returning as "undefined"
routeConfigProvider.getRoutes().forEach(function(r) {
$routeProvider.when(r.url, r.config);
});
$routeProvider.otherwise({ redirectTo: '/' });
}
]);
})();
Created a plunkr demo : http://plnkr.co/edit/2TIqgxMxBJEPbnk2Wk6D?p=preview
(Regarding your last comment, with the plnkr)
The result is expected.
At config time (within app.config() ), you access raw providers, as you defined them, which allows you to call "private" methods or fields (testItem1) and to configure it for run time use. "private" because they won't be accessible at run time.
At run time (within app.run() and the rest of your app), when you ask for a dependency for which you wrote a provider, the angular injector hands you the result of the $get method of your provider, not the provider itself, so you can't access the "private" function.
This page was my path to enlightenment : AngularJS: Service vs provider vs factory
I think you may be over complicating the route stuff. You may have a very good reason for it but as I do not know it may I suggest keeping it simple with something more like this:
MyApp.config(function ($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController',
activeTab: 'home'
})
};
MyApp.controller('HomeController', function ($route) {
console.log($route.current.activeTab);
});
I would be interested in knowing why you may not able to use this routing pattern or purposely chose something different.
I think it has to do with the way you are creating your initial module. Try this:
var app = angular.module('app', []);
app.constant('configuration', {
PARTIAL_PATH: "/app/components/partials"
});
var routeServiceModule = angular.module('routeService', ['app']);
I have an interesting issue with the $http.delete() and $window.location.reload() functions. Basically I am calling a delete method that in turn calls the $http.delete() call which - using a REST API interface - removes data from a database (mongoDB). For reasons unknown this is what's happening:
delete is successful in the database
this is verified as the data is no longer in the database
also monitored using Chrome DevTools it shows status: 200
$window.location.reload() gets called and nothing happens
Chrome DevTools shows a GET call to the root of the domain but the status is 'pending'
The page does not time out, it basically keeps on loading and loading and loading. Once I hit refresh / CTRL-F5 all goes back to normal and I can see that my item has been deleted.
Some excerpts from my code:
app.js
angular.module('contacts', ['ngRoute', 'contacts.factory', 'contacts.filters', 'ui.bootstrap']).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: '/p/list',
controller: ListCtrl,
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
controllers.js
function ListCtrl($scope, $modal, contactFactory) {
//code removed
$scope.delete = function(c) {
var id = c._id;
var modalInstance = $modal.open({
templateUrl: 'deleteContactModal',
controller: deleteContactModalCtrl,
resolve: {
contact: function() {
return contactFactory.getContact(id);
}
}
});
}
}
var deleteContactModalCtrl = function($scope, $route, $modalInstance, $window, contact, contactFactory) {
$scope.name = contact.data.contact.name;
$scope.deleteContact = function() {
contactFactory.deleteContact(contact.data.contact._id).success(function() {
//have also tried: $window.location.reload(true);
//as well as window.location.href('/') - didn't work either
$modalInstance.close($window.location.reload());
});
};
}
factory.js
angular.module("contacts.factory", []).
factory('contactFactory', function($http){
return {
//code removed
deleteContact: function(id) {
return $http.delete('/api/contact/' + id);
}
}
});
backend - app.js
//usual express setup
app.delete('/api/contact/:id', api.delete); //delete contact
backend - api.js
//code removed
exports.delete = function (req, res) {
var id = req.params.id;
if (id) {
ContactModel.findById(id, function (err, contact) {
contact.remove(function (err) {
if (!err) {
res.json(true);
} else {
res.json(false)
console.log(err);
}
});
});
}
};
At the moment I'm not even sure if this issue is related to the frontend or to the backend. As mentioned before - the backend portion is working fine - the data is deleted from the DB.
Okay the solution seems to be the following:
$scope.deleteContact = function() {
contactFactory.deleteContact(contact.data.contact._id).success(function() {
$modalInstance.close();
contactFactory.getContacts().success(function(contacts) {
return $scope.contacts = contacts;
});
$window.location.reload();
});
};
I need to get the getContacts() method from my factory again during the delete method.
I'm having trouble figuring out how to get the routeProvider to wait until a remote call returns. The best solution I've seen for far was the example here: delaying angular route change
. Unfortunately, when I tired to apply that example to my own code, the binding would trigger before the data was actually loaded. Does anyone know of another example that uses the new Resource syntax from angular 1.1.5 ($promise can be accessed directly )?
Here is what my code looks like:
var productModule = angular.module('productModule', ['ngResource', 'ngLocale']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html',
controller: 'ResourceCtrl as appController' ,
resolve:
{
productData: function($resource)
{
console.log(["calling service"]);
return $resource(Services.ProductServices.PATH).query(null,
function(data){
console.log(["call succeeded"]);
},
function(data){
console.log(["calling failed"]);
}).$promise;
}
}
});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]) ;
productModule.controller('ResourceCtrl','$scope','productData',function($scope,productData) {
$scope.productData = productData;
console.log(["promise resolved"]);
}]);
If I run that code, the console would display:
calling service
promise resolved
call succeeded
It should be as simple as this:
resolve: {
productData: function(ProductServices) {
return ProductServices.query().$promise.then(function(data){
return data;
});
}
}
If your Service looks something like this:
myApp.factory('ProductServices', function($resource) {
return $resource('/path/to/resource/:id', { id: '#id' });
});