I have a project in Meteorjs which uses iron:router package. The problem is that, after I have updated the Meteorjs project to 1.4, iron:router doesn't execute it's function. I tried a few workarounds such as reinstalling of package, followed also the updates of iron:router syntax, still no good. I will show a sample chunk of code.
Router.route('/', function () {
this.render('home_t', {});
this.render('cover_t', {to: 'beforehead'});
this.render('front_t', {to: 'front'});
}, {
controller: 'BasicController',
onBeforeAction: function () {
document.title = "Bfash | Home";
this.next();
},
name: 'home_r'
});
Router.route('/products', function () {
this.render('products_t', {});
}, {
controller: 'BasicController',
onBeforeAction: function () {
document.title = "Bfash | Products";
this.next();
},
name: 'products_r'
});
Router.route('/item/:_id/:ownerid', function () {
Session.set('itemid', this.params._id);
Session.set('ownerid', this.params.ownerid);
this.render('item_t', {});
if (Roles.userIsInRole(Meteor.userId(), ['users'])){
this.render('chat_t', {to: 'chatmessages'});
}
//if IP address
Meteor.call('mostview_products',this.params._id,function(err){
if(err){
console.log(err);
}else{
console.log('added');
}
})
}, {
controller: 'BasicController',
onBeforeAction: function () {
document.title = "Bfash | Item";
this.next();
},
name: 'item_r'
});
Router.route('/store/:name/:ownerid/:categoryid', function () {
Session.set('ownerid', this.params.ownerid);
Session.set('categoryid', this.params.categoryid);
this.render('category_t', {});
}, {
controller: 'BasicController',
onBeforeAction: function () {
document.title = "Bfash | Category";
this.next();
},
name: 'category_r'
});
Related
I have the following routes file in components/app/app-routes.js:
export default
function AppRoutes($stateProvider, $urlRouterProvider, $transitionsProvider) {
'ngInject';
// reference: https://ui-router.github.io/guide/ng1/migrate-to-1_0#lazy-resolves
const defaultResolvePolicy = {
when: 'EAGER'
};
const STATES = [{
name: 'logout',
url: '/logout?applicationName&desktopName&sn',
}, {
name: 'base',
url: '',
abstract: true,
template: '<ui-view></ui-view>'
}, {
name: 'app',
parent: 'base',
abstract: true,
component: 'wireApp',
data: {
authRequired: true
},
resolvePolicy: defaultResolvePolicy,
resolve: {
labels(LabelService) {
'ngInject';
return LabelService.fetch();
},
settings(SettingsService) {
'ngInject';
return SettingsService.fetch();
},
}
}, {
name: '404',
url: '/404',
parent: 'base',
template: '<w-404></w-404>',
resolvePolicy: defaultResolvePolicy,
resolve: {
module($q, $ocLazyLoad) {
'ngInject';
return $q((resolve) => {
require.ensure([], (require) => {
let mod = require('pages/404');
$ocLazyLoad.load({
name: mod.name
});
resolve(mod.name);
}, '404');
});
},
}
}, {
name: 'dashboard',
parent: 'app',
url: '/dashboard',
data: {
authRequired: true
},
views: {
'content#app': {
template: '<w-dashboard priority-tasks="$resolve.priorityTasks"></w-dashboard>'
},
},
resolvePolicy: {
module: defaultResolvePolicy,
priorityTasks: {
when: 'LAZY'
},
},
resolve: {
priorityTasks($http, $q, CacheFactory, CustomerService, RuntimeConfig, PermissionService) {
'ngInject';
if (!CacheFactory.get('priorityTasks')) {
CacheFactory.createCache('priorityTasks', {
storageMode: 'sessionStorage',
storagePrefix: 'w'
});
}
const priorityTasksCache = CacheFactory.get('priorityTasks');
if (PermissionService.check('PRIORITY_TASKS', 'view')) {
return $http.get(`${RuntimeConfig.DEV_API_URL}/customer/${CustomerService.model.currentCustomer.id}/priority-tasks`, {
cache: priorityTasksCache
}).then(({
data
}) => data, () => $q.resolve([]));
}
return [];
},
module($q, $ocLazyLoad) {
'ngInject';
return $q((resolve) => {
require.ensure([], (require) => {
let mod = require('pages/dashboard');
$ocLazyLoad.load({
name: mod.name
});
resolve(mod.name);
}, 'dashboard');
});
}
}
}, {
name: 'loans',
parent: 'app',
url: '/loans',
data: {
authRequired: true
},
views: {
'content#app': {
template: '<w-loans></w-loans>',
},
},
resolvePolicy: defaultResolvePolicy,
resolve: {
security($q, $state) {
'ngInject';
//irl get this from a service.
console.log($transitionsProvider, "TRANSISIONS PROVIDER FROM ROUTE");
// let permissions = false;
// if (!permissions) {
// return $q.reject("No permissions");
// }
},
module($q, $ocLazyLoad) {
'ngInject';
return $q((resolve) => {
require.ensure([], (require) => {
let mod = require('pages/loans');
$ocLazyLoad.load({
name: mod.name
});
resolve(mod.name);
}, 'loans');
});
}
}
}];
$urlRouterProvider
.when('', '/dashboard')
.when('/', '/dashboard')
.when('/login', '/dashboard')
.otherwise('/404');
//this will redirect all rejected promises in routes to a 404.
$transitionsProvider.onError({
to: '*',
from: '*'
}, (transition) => {
let $state = transition.router.stateService;
$state.go('404');
});
STATES.forEach((state) => {
$stateProvider.state(state);
});
}
in my loans controller (associated state above, 'loans'), however, I am unable to access the new uiCanExit callback.:
.component('wLoans', {
template: require('./loans.html'),
controller: LoansController,
bindings: {
settings: '<',
labels: '<'
}
});
function LoansController($window, $timeout, $http, $compile, $log, $filter, LoansService, ConfigService, ngDialog, SettingsService, CustomerService, ColumnRenderService, $transitions) {
'ngInject';
this.uiCanExit = function () {
console.log("WHY AM I NOT GETTING HERE");
}
}
nothing appears in the console when I switch between states, and I'm trying to figure out what to do to get the uiCanExit lifecycle hook to be run when I switch in between states (particularly dashboard and loans)
I'm not sure about this, but could the problem be caused by not referencing the component directly? Probably this only works when you reference your loans component via the component key instead of placing them in a template which renders the component. I assume that in your case the router tries to find the callback in the (not declared and thus dummy) controller instead of using the component's controller.
Please have a look at the docs: https://ui-router.github.io/docs/latest/interfaces/ng1.ng1controller.html#uicanexit
You can validate this assumption by putting a controller implementation with the uiCanExit() method in your loans state.
I'm using the ui-bootstrap modal window and I'm trying to test a method that fires that modal window. My controller:
app.controller('AddProductController', ['$scope', 'ProductsService', '$uibModal', function ($scope, ProductsService, $uibModal) {
$scope.product = {};
$scope.searchCategories = function () {
ProductsService.getRootCategories().then(function (data) {
$scope.categories = data.data;
});
$scope.modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'categoryContent.html',
controller: 'AddProductController',
scope: $scope
});
$scope.modalInstance.result.then(function (category) {
$scope.searchCategory = null;
$scope.product.category = category;
}, function () {
});
};
$scope.ok = function(){
$scope.modalInstance.close($scope.product.category);
};
$scope.cancel = function(){
$scope.modalInstance.dismiss();
}]);
And my test:
describe("Products Controller", function () {
beforeEach(function () {
module('productsController');
});
beforeEach(function () {
var ProductsService, createController, scope, rootScope,
module(function ($provide) {
$provide.value('ProductsService', {
getRootCategories: function () {
return {
then: function (callback) {
return callback({data: {name: 'category1'}});
}
};
},
});
$provide.value('$uibModal', {
open : function(){
return {
then: function (callback) {
return callback({data: {name: 'category1'}});
}
};
}
});
return null;
});
});
describe('AddProductController', function () {
beforeEach(function () {
inject(function ($controller, _$rootScope_, _ProductsService_) {
rootScope = _$rootScope_;
scope = _$rootScope_.$new();
ProductsService = _ProductsService_;
createController = function () {
return $controller("AddProductController", {
$scope: scope,
});
};
});
});
it('calling searchCategories should make $scope.categories to be defined', function () {
createController();
expect(scope.categories).not.toBeDefined();
scope.searchCategories();
expect(scope.categories).toBeDefined();
});
});
});
All my tests pass,except this one, where I get TypeError: $scope.modalInstance.result is undefined.
Any clues?
It seems you're not defining result in your mock modal. Try something like this:
$provide.value('$uibModal', {
open: function () {
return {
result : {
then: function (callback) {
return callback({ data: { name: 'category1' } });
}
}
};
}
});
I am having issues trying to access a service on a controller. The issue happen when the Ordenes services is called. How I can call a service with two parameter using values from the scope from a controller using ui-router?
I have the same code working but without the use of ui-router. It seems like the code is not loading properly the service inside the Controller.
App.js
'use strict';
app = angular.module('logica-erp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.router',
'authorization',
'ui.router.stateHelper',
'logica-erp.kds',
'logica-erp.pos'
])
app.run(function($rootScope) {
$rootScope.$on("$stateChangeError", console.log.bind(console));
});
app.config(function ($stateProvider, $urlRouterProvider) {
//delete $httpProvider.defaults.headers.common['X-Requested-With'];
$urlRouterProvider.otherwise('/');
$stateProvider
.state('index', {
url: '/',
templateUrl: 'views/main.html',
controller:'MainCtrl'
})
.state('comanda', {
url: '/comanda',
templateUrl: 'views/comanda.html',
controller:'ComandaCtrl'
})
.state('counter', {
url: '/counter',
templateUrl: 'views/counter.html',
controller:'CounterCtrl'
})
})
comanda.js
(function() {
'use strict';
var app;
app = angular.module('logica-erp.kds', ['timer', 'logica-erp.service.pos']);
this.ComandaCtrl = [
'$scope', '$interval', 'Ordenes', function($scope, $interval, Ordenes) {
var error, stop, success, tick;
$scope.tiempos = [
{
name: '15 seg',
value: 15000
}, {
name: '30 seg',
value: 30000
}, {
name: '60 seg',
value: 60000
}, {
name: '120 seg',
value: 120000
}
];
$scope.selected_tiempo = $scope.tiempos[1];
$scope.tipos = [
{
name: 'Alimentos',
value: 'a'
}, {
name: 'Bebidas',
value: 'b'
}, {
name: 'Todos',
value: ''
}
];
$scope.selected_tipo = $scope.tipos[2];
success = function(result) {
if (angular.toJson(result) !== angular.toJson($scope.ordenes)) {
$scope.isLoading = true;
$scope.ordenes = result;
console.log(JSON.stringify($scope.ordenes));
}
return $scope.isLoading = false;
};
error = function(error) {
console.log('error ' + error);
return $('#modal').foundation('open');
};
tick = function() {
$scope.platos = Ordenes.query({
tipo: $scope.selected_tipo.value,
sucursal: 2
});
return $scope.platos.$promise.then(success, error);
};
tick();
stop = $interval(tick, $scope.selected_tiempo.value);
$scope.change_refresh = function() {
$interval.cancel(stop);
return stop = $interval(tick, $scope.selected_tiempo.value);
};
return $scope.update_order = function(mesa, aaybb_id) {
return angular.forEach($scope.ordenes.mesas, function(orden) {
if (orden.mesa === mesa) {
return angular.forEach(orden.aaybb, function(aaybb) {
if (aaybb._id === aaybb_id) {
if (aaybb.estatus === 'ASIGNADO') {
aaybb.estatus = 'EN PROCESO';
} else if (aaybb.estatus === 'EN PROCESO') {
aaybb.estatus = 'PREPARADO';
$('#timer_' + aaybb._id)[0].stop();
}
return Ordenes.update(aaybb);
}
});
}
});
};
}
];
app.controller('ComandaCtrl', ComandaCtrl);
}).call(this);
Console log
Error: value is undefined
extractParams/<#http://127.0.0.1:9000/bower_components/angular-resource/angular-resource.js:344:11
forEach#http://127.0.0.1:9000/bower_components/angular/angular.js:336:11
extractParams#http://127.0.0.1:9000/bower_components/angular-resource/angular-resource.js:343:9
ResourceFactory/</Resource[name]#http://127.0.0.1:9000/bower_components/angular-resource/angular-resource.js:398:39
this.ComandaCtrl</tick#http://127.0.0.1:9000/scripts/controllers/comanda.js:72:25
this.ComandaCtrl<#http://127.0.0.1:9000/scripts/controllers/comanda.js:78:7
I fixed the issue, it was a old bug in the angular-resource lib. I didn't know but my bower was installing version 1.0.7 :S anyway; this was very annoying.
I am trying to dynamically load a route based on a user's most recent visit to a child route. The most recent visit is saved and is retrieved using a factory. currently I am using onEnter but that causes the parent route to load and then a second load to happen to load the child route. Is there a way to prevent the second load and go directly to the child route if the needed information is there?
(function() {
'use strict';
angular
.module('curation')
.config(routesConfig);
routesConfig.$inject = ['$stateProvider'];
/**
* Route Configuration to establish url patterns for the module
* #param {Function} $stateProvider
*/
function routesConfig($stateProvider) {
// Curation state routing
$stateProvider.
state('site.curation', {
url: '/curation',
templateUrl: 'modules/curation/views/curation.client.view.html',
resolve: {
publicFronts: function($stateParams, frontsService) {
return frontsService.getPublicFronts($stateParams.siteCode);
},
authoringTypes: function(assetMetadata) {
return assetMetadata.authoringTypes().then(function(value) {
return value.data.authoringTypes;
});
}
},
onEnter: function($state, $timeout, userSitePreferences, publicFronts) {
$timeout(function() {
var recentFront = _.find(publicFronts, {
Id: userSitePreferences.curation.recentFrontIds[0]
});
if (recentFront) {
$state.go('site.curation.selectedFront.selectedLayout', {
frontId: recentFront.Id,
layoutId: recentFront.LayoutId
});
}
});
}
});
}
})();
Try out "Deep State Redirect" of the "ui-router-extras".
http://christopherthielen.github.io/ui-router-extras/#/dsr
Try something like this...
$stateProvider.
state('site.curation', {
url: '/curation',
templateUrl: 'modules/curation/views/curation.client.view.html',
resolve: {
publicFronts: function($stateParams, frontsService) {
return frontsService.getPublicFronts($stateParams.siteCode);
},
authoringTypes: function(assetMetadata) {
return assetMetadata.authoringTypes().then(function(value) {
return value.data.authoringTypes;
});
}
},
deepStateRedirect: {
default: {
state: 'site.curation.selectedFront.selectedLayout'
params: {
frontId: 'defaultId',
layoutId: 'defaultLayout'
}
},
params: true,
// I've never tried to generate dynamic params, so I'm not sure
// that this accepts DI variables, but it's worth a try.
fn: function ($dsr$, userSitePreferences, publicFronts) {
var recentFront = _.find(publicFronts, {
Id: userSitePreferences.curation.recentFrontIds[0]
});
if (recentFront) {
return {
state: $dsr$.redirect.state,
params: {
frontId: recentFront.Id,
layoutId: recentFront.LayoutId
}
};
} else {
return false;
}
});
}
});
app.admin.routes.js
(function () {
'use strict';
angular
.module('app.admin')
.run(appRun);
appRun.$inject = ['routeHelper', 'app.core.services.notificationService'];
function appRun(routeHelper, notificationService) {
debugger;
routeHelper.configureRoutes(getRoutes());
function getRoutes() {
return [
{
state: 'admin',
url: '/admin',
templateUrl: 'app/features/admin/admin.html',
controller: 'Admin as vm',
resolve: {
// signalRConnection: function() {
// return notificationService.onReady;
// }
},
settings: {
navigation: {
group: "application",
label: "Admin",
//label: "navigation.admin",
icon: "fa-lock",
order: 2
}
//content: '<i class="fa fa-lock"></i> Admin'
}
}
];
}
}
})();
admin.js
(function () {
'use strict';
angular
.module('app.admin')
.controller('Admin', Admin);
Admin.$inject = ['logger'];
function Admin(logger) {
/*jshint validthis: true */
var vm = this;
vm.title = 'Admin';
activate();
function activate() {
logger.info('Activated Admin View');
}
}
})();
adminctrlSpec.js
describe("AdminController", function () {
var _logger;
beforeEach(function() {
module("app.admin", function ($provide) {
$provide.value('routeHelper', {
configureRoutes: function(routes) {
}
});
$provide.value('app.core.services.notificationService', {
signalRConnection: function () {
}
});
});
});
beforeEach(function () {
inject([
'logger', function (logger) {
debugger;
}
]);
});
it("asd", function() {
debugger;
});
});
I am able to use logger in all of my other Specs. But unable to inject for admin.js.
beforeEach(function () {
> inject([
> 'logger', function (logger) {
> debugger;
> }
> ]);
> });
Error: [$injector:unpr] Unknown provider: loggerProvider <- logger
(function () {
'use strict';
angular.module('app', [
'app.admin',
'app.modelling',
'app.layout'
]);
})();
Problem solved .i forgot to add beforeEach(function () { module("app"); });