Sending data from a service to a factory - angularjs

Hey guys I am trying to send a variable from a service from auth.service.js to a factory which is in app.js. I am kind of new to angular so I appreciate any help.
(function() {
'use strict';
angular
.module('app')
.service('authService', authService);
authService.$inject = ['$rootScope', 'lock', 'authManager', 'jwtHelper'];
function authService($rootScope, lock, authManager, jwtHelper) {
var userProfile = JSON.parse(localStorage.getItem('profile')) || {};
function login() {
lock.show();
}
// Logging out just requires removing the user's
// id_token and profile
function logout() {
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
authManager.unauthenticate();
userProfile = {};
}
// Set up the logic for when a user authenticates
// This method is called from app.run.js
function registerAuthenticationListener() {
lock.on('authenticated', function(authResult) {
localStorage.setItem('id_token', authResult.idToken);
authManager.authenticate();
var pubkey = KEYUTIL.getKey('-----BEGIN CERTIFICATE-----MIIC8DCCAdigAwIBAgIJVUYCZUQdreDfMA0GCSqGSIb3DQEBBQUAMB8xHTAbBgNVBAMTFHN3aXRjaC1hcHAuYXV0aDAuY29tMB4XDTE2MTAwNTE5MzczM1oXDTMwMDYxNDE5MzczM1owHzEdMBsGA1UEAxMUc3dpdGNoLWFwcC5hdXRoMC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTG7oTPof81dqHqDKT8Mi/umpKgALMHJRwXSVIPBtPZGrgyOubi1oPsWZQrYOwla/3fMhstV/g6ZclVLGg9YHwNZl7uZYaOhAX1CjaTnDUe85R0lvFMRO42N5ZdbhXQASPPrMNZL7gov3eBQcj2n+Jb2k7OWYpN2mevw1fd6iah0eKAeoUcoWGjYwkB9DLmN7HizRsMHeVRyx3BJisI1PmFMkR+Ewbdu+HtOf7yavaVS6KmJti/U/192mXDgakRBLeODrZ+AxwedYcaF4CtGyS52SKkkHsbi6KsjDjfc9CbRRM+51VffVNzTsMTHYtADG34KHigGry/x/5QfsCAEXnAgMBAAGjLzAtMAwGA1UdEwQFMAMBAf8wHQYDVR0OBBYEFOUsGT48yyeHc6a/RdMAlasaM3p7MA0GCSqGSIb3DQEBBQUAA4IBAQAeqkTdeYqE1gSauYr/h30OSjxvHgskUOueWvFBnFveiEQWV3eVyu/psn2YG/2QgCeNSWUMsd8SXCAOBilFy6GL27bUmGKoZEDYsm0dUFTxZiTHgJZNMMQIpPtCLw48Ly1BVQQvi21DZnS9G5ZdWbTEwjNK4M+Fil5zgaiJaObRH4+oAXpgwngT+ZoEO3Z38urbs/Gcp1VKvHjEdY18JxyDChQfIDQNb6bc2zoOR62JTx75fC7khQesJ2jcxJhE1VLsvMRr1bVaVgBeEAdq+fC6WQsJA08209JmJfO4/OYscSe9RxnDEXa6UOQpNO34x5Tr8AImQTLy3jdFoNg1/fSL-----END CERTIFICATE-----');
var isValid = KJUR.jws.JWS.verifyJWT(authResult.idToken, pubkey, {alg: ['RS256']});
console.log(isValid);
// Used for decoding the message returned form auth0
var decoded = jwt_decode(authResult.idToken);
// The encoded message returned from auth0
console.log(authResult.idToken);
//The decoded message returned from auth0
console.log(decoded);
lock.hide();
// Redirect to default page
location.hash = '#/app/home';
lock.getProfile(authResult.idToken, function(error, profile) {
if (error) {
console.log(error);
}
localStorage.setItem('profile', JSON.stringify(profile));
});
});
}
function checkAuthOnRefresh() {
var token = localStorage.getItem('id_token');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!$rootScope.isAuthenticated) {
authManager.authenticate();
}
}
}
}
return {
userProfile: userProfile,
login: login,
logout: logout,
registerAuthenticationListener: registerAuthenticationListener,
checkAuthOnRefresh: checkAuthOnRefresh
}
}
})();
I want to send from the function registeredAuthentificationListener() the authResult.idToken to a factory in
app.js
(function () {
var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (iOS) {
var isApple = 'isApple';
}else{
var isApple = 'notApple';
}
'use strict';
var app = angular
.module('app', ['ionic', 'auth0.lock', 'angular-jwt'])
.config(config);
config.$inject = ['$stateProvider', '$urlRouterProvider', 'lockProvider', 'jwtOptionsProvider','$httpProvider'];
function factory() {
return {
request : function (config) {
config.headers['X-switch-using'] = isApple;
return config;
}
}
}
function config($stateProvider, $urlRouterProvider, lockProvider, jwtOptionsProvider,$httpProvider) {
$stateProvider
// setup an abstract state for the tabs directive
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'components/menu/menu.html',
})
.state('app.home', {
url: '/home',
views: {
'menuContent': {
templateUrl: 'components/home/home.html'
}
}
})
.state('app.dashboard', {
url: '/dashboard',
views: {
'menuContent': {
templateUrl: 'components/template/template.html'
}
}
})
.state('app.signin', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'components/login/login.html'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/home');
$httpProvider.interceptors.push(factory);
lockProvider.init({
clientID: AUTH0_CLIENT_ID,
domain: AUTH0_DOMAIN,
options: {
auth: {
redirect: false,
params: {
scope: 'openid',
device: 'Mobile device'
}
}
}
});
// Configuration for angular-jwt
jwtOptionsProvider.config({
tokenGetter: function() {
return localStorage.getItem('id_token');
},
whiteListedDomains: ['localhost'],
unauthenticatedRedirectPath: '/login'
});
}
})();
Thank you for your help!

It's my bad, you can send the variable using localStorage.getItem('id_token') and use that straight in the app.js

Related

UI router login form submission

I currently have code for a form submission login that works with ng-route, however i want to convert it to UI router. I currently have MVC java controller for rest services. However here is my main app with configure statements:
var reportingDashboard = angular
.module('reportingDashboard', [ 'ngRoute', 'ui.router', 'ngMdIcons', 'chart.js'])
.config(
function($routeProvider, $httpProvider, $stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
/* $routeProvider.when('/', {
templateUrl : '/home/temp.html',
controller : 'home',
controllerAs : 'controller'
}).when('/login', {
templateUrl : '/home/loginCtrl/login.html',
controller : 'navigation',
controllerAs : 'controller'
}).otherwise("/")
*/
$urlRouterProvider.otherwise('/');
$stateProvider
.state('login',{
url:'/login',
templateUrl : '/home/loginCtrl/login.html',
controller : 'navigation',
controllerAs : 'controller'
})
.state('home',{
url:'/',
templateUrl : '/home/temp.html',
controller : 'home',
controllerAs : 'controller'
})
.state('home.index', {
views:{
'': {
templateUrl:"/home/reportingTemp/repoHtml.html"
},
'reportingGraph':{
templateUrl:'/home/reportingTemp/repoGraph.html',
controller: 'reportingGraphCtrl'
}
}
})
.state('home.admin', {
views:{
'': {
templateUrl:"/home/adminTemp/adminHtml.html"
},
'adminGraph':{
templateUrl:'/home/adminTemp/adminReport.html',
controller:'adminCtrl'
}
}
})
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).run(function(auth) {
// Initialize auth module with the home page and login/logout path
// respectively
console.log("is the auth function being called?")
auth.init('/', '/login', '/logout');
});
From this I have the auth factory:
reportingDashboard.factory(
'auth',
function($rootScope, $http, $location) {
enter = function() {
if ($location.path() != auth.loginPath) {
console.log($location.path());
auth.path = $location.path();
if (!auth.authenticated) {
$location.path(auth.loginPath);
}
}
}
var auth = {
authenticated : false,
loginPath : '/login',
logoutPath : '/logout',
homePath : '/',
path : $location.path(),
authenticate : function(credentials, callback) {
var headers = credentials && credentials.username ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
auth.authenticated = true;
} else {
auth.authenticated = false;
console.log("The use isnt logged in")
}
callback && callback(auth.authenticated);
$location.path(auth.path==auth.loginPath ? auth.homePath : auth.path);
}).error(function() {
auth.authenticated = false;
callback && callback(false);
});
},
clear : function() {
$location.path(auth.loginPath);
auth.authenticated = false;
$http.post(auth.logoutPath, {}).success(function() {
console.log("Logout succeeded");
}).error(function(data) {
console.log("Logout failed");
});
},
init : function(homePath, loginPath, logoutPath) {
auth.homePath = homePath;
auth.loginPath = loginPath;
auth.logoutPath = logoutPath;
auth.authenticate({}, function(authenticated) {
if (authenticated) {
$location.path(auth.path);
}
})
// Guard route changes and switch to login page if unauthenticated
$rootScope.$on('$routeChangeStart', function() {
enter();
});
}
};
return auth;
});
From this I have the navigation controller:
reportingDashboard.controller(
'navigation',
function($route, auth, $location) {
var self = this;
self.credentials = {};
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
self.authenticated = function() {
return auth.authenticated;
}
self.login = function() {
auth.authenticate(self.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
self.error = false;
} else {
console.log("Login failed")
self.error = true;
}
})
};
self.logout = auth.clear;
});
Also i have the home controller as well:
reportingDashboard.controller('home', function($http) {
var self = this;
$http.get('/user/').success(function(data) {
self.user = data.name;
});
});
the console just returns a 401 and redirects me to the home page of the application. Any advice would be great Thankyou!! I can include any more info if it helps.
My suggestion: in angular.run function bind listener to $stateChangeStart event. Each time user will go to some state, you will check that user is authenficated. If he is, continue transition, else - save transition state and params, go to login page and after user will successfully logged in, you will redirect him to requested state/page. Something like this:
myApp.run(function ($rootScope, principal, $state, myStateProvider, userService) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
if (toState.name !== 'login') {
myStateProvider.setNextState(toState, toParams);
}
if (!principal.isAuthenticated()) {
event.preventDefault();
principal.checkAuthentication().then(function() {
$state.go(toState, toParams);
});
} else if (principal.isAuthenticated() && toState.name === 'login') {
event.preventDefault();
myStateProvider.redirectFromLogin();
}
});
})

how to Inject Interceptor service in angularAMD config option

I am using angularAMD with require js and I have written an interceptor service which I want to register with $httpProvider.interceptors in my app config file but it throwing error as
Error: [$injector:unpr]
http://errors.angularjs.org/1.4.8/$injector/unpr?p0=cookieInjectorProvider%…eInjector%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24compile(…)
Below is my implimentation
define(["angularAMD", "angular-route", "ui-bootstrap","ngCookies","common/service/interceptor-service"], function(angularAMD){
"use strict";
var app = angular.module("app", ["ui.router", "ui.bootstrap","ngAnimate","ngTouch","angular-carousel","ngCookies"]);
//route
app.config(["$stateProvider", "$urlRouterProvider", "$locationProvider","$httpProvider", function($stateProvider, $urlRouterProvider, $locationProvider,$httpProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state("home", angularAMD.route({
url: "/",
views: {
'header':{
/*...*/
},
},
'content': {
/*...*/
},
'footer': {
/*...*/
}
}));
**//angular is not able to find 'cookieInjector' service**
$httpProvider.interceptors.push('cookieInjector');
}]);
// Bootstrap Angular when DOM is ready
return angularAMD.bootstrap(app, false, document.getElementsByTagName("body")[0]);
});
and my "cookieInjector file is" this service requires another service and it is also implemented in a similar way
define([
'angularAMD',
"common/service/cookie-service"
], function(angularAMD){
angularAMD.service("cookieValidator",[function(){
this.isLoggedIn = false;
this.getIsLoggedIn = function(){
return this.isLoggedIn;
};
this.setIsLoggedIn = function(status){
this.isLoggedIn = status;
};
}])
.factory('cookieInjector', ['$q','cookieValidator', 'cookieService',function($q,cookieValidator,cookieService) {
var cookieInjector = {
request: function(config) {
var cookie = cookieService.getCookie();
if(!cookie){
cookieValidator.setIsLoggedIn(false);
//$location.path('/login');
}else{
cookieValidator.setIsLoggedIn(true);
}
config.headers['Token'] = cookie ? cookie : null;
return config;
},
response: function(response) {
response.config.responseTimestamp = new Date().getTime();
return response;
},
responseError: function(response) {
// Cookie has expired
if(response.status === 401 || response.status === 403) {
cookieService.destroyCookie();
cookieValidator.setIsLoggedIn(false);
}
return $q.reject(response);
}
};
return cookieInjector;
}]);
})
I am stuck completely. Thanks for any help.
angular is not able to find 'cookieInjector' service
This is probably because cookieInjector is not available at the moment app.config run. From what I remember angularAMD.factory() will only enject your factory/service into you app after app.config() has been ran.
So in this case, another global angular module should be used instead of using angularAMD
create a file cookieInjector.js
angular.module('cookieModule', []).facotry('cookieInjector', ['$q', 'cookieValidator', 'cookieService', function($q, cookieValidator, cookieService) {
var cookieInjector = {
request: function(config) {
var cookie = cookieService.getCookie();
if (!cookie) {
cookieValidator.setIsLoggedIn(false);
//$location.path('/login');
} else {
cookieValidator.setIsLoggedIn(true);
}
config.headers['Token'] = cookie ? cookie : null;
return config;
},
response: function(response) {
response.config.responseTimestamp = new Date().getTime();
return response;
},
responseError: function(response) {
// Cookie has expired
if (response.status === 401 || response.status === 403) {
cookieService.destroyCookie();
cookieValidator.setIsLoggedIn(false);
}
return $q.reject(response);
}
};
return cookieInjector;
}]);
Then init can config your app.
// requireJS config
requirejs.config({
path:{
cookieInjector: 'path/to/cookieInjector'
}
// ... your codes
shim: {
// ... your codes
// make sure cookie injector only load after angularJS is loaded.
cookieInjector: ["angular"];
}
});
// your app.js (?) file
define(["angularAMD", "cookieInjector", "angular-route", "ui-bootstrap", "ngCookies", "common/service/interceptor-service"], function(angularAMD) {
"use strict";
var app = angular.module("app", ["cookieModule", "ui.router", "ui.bootstrap", "ngAnimate", "ngTouch", "angular-carousel", "ngCookies"]);
//route
app.config(["$stateProvider", "$urlRouterProvider", "$locationProvider", "$httpProvider", function($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state("home", angularAMD.route({
url: "/",
views: {
'header': {
/*...*/
},
},
'content': {
/*...*/
},
'footer': {
/*...*/
}
}));
// It should be loaded now
$httpProvider.interceptors.push('cookieInjector');
}]);
// Bootstrap Angular when DOM is ready
return angularAMD.bootstrap(app, false, document.getElementsByTagName("body")[0]);
});

Angularjs role based routing error

I am trying to implement role based authorization in beeman's loopback-angular-admin repo by using this https://github.com/Narzerus/angular-permission
so I am trying to change the users.config.js to like this -
(function () {
'use strict';
angular.module('com.module.users')
.run(function ($rootScope, gettextCatalog, Permission, AppAuth, User) {
$rootScope.addMenu(gettextCatalog.getString('Users'), 'app.users.list', 'fa-user');
Permission.defineRole('anonymous', function (stateParams) {
// If the returned value is *truthy* then the user has the role, otherwise they don't
return !AppAuth.hasOwnProperty('currentUser');
});
Permission.defineRole('student', function (stateParams) {
// If the returned value is *truthy* then the user has the role, otherwise they don't
AppAuth.ensureHasCurrentUser(function () {
//This call also serves to redirect a user to the login screen, via the interceptor in users.auth.js, if they are not authenticated.
console.log(User.getCurrent());
return !!(User.getCurrent().hasOwnProperty('role') && User.getCurrent().role == 'student');
});
}).defineRole('tutor', function (stateParams) {
// If the returned value is *truthy* then the user has the role, otherwise they don't
AppAuth.ensureHasCurrentUser(function () {
//This call also serves to redirect a user to the login screen, via the interceptor in users.auth.js, if they are not authenticated.
console.log(User.getCurrent());
return !!(User.getCurrent().hasOwnProperty('role') && User.getCurrent().role == 'tutor');
});
});
});
})();
So basically I am defining my roles with the help of AppAuth module that has the following code -
(function () {
'use strict';
/*jshint sub:true*/
/*jshint camelcase: false */
angular
.module('com.module.users')
.factory('AppAuth', function ($cookies, User, LoopBackAuth, $http) {
var self = {
login: function (data, cb) {
LoopBackAuth.currentUserId = LoopBackAuth.accessTokenId = null;
$http.post('/api/users/login?include=user', {
email: data.email,
password: data.password
})
.then(function (response) {
if (response.data && response.data.id) {
LoopBackAuth.currentUserId = response.data.userId;
LoopBackAuth.accessTokenId = response.data.id;
}
if (LoopBackAuth.currentUserId === null) {
delete $cookies['accessToken'];
LoopBackAuth.accessTokenId = null;
}
LoopBackAuth.save();
if (LoopBackAuth.currentUserId && response.data && response.data
.user) {
self.currentUser = response.data.user;
cb(self.currentUser);
} else {
cb({});
}
}, function () {
console.log('User.login() err', arguments);
LoopBackAuth.currentUserId = LoopBackAuth.accessTokenId =
null;
LoopBackAuth.save();
cb({});
});
},
logout: function (cb) {
//Destroy the access token.
User.logout({"access_token": LoopBackAuth.accessTokenId}, function () {
//Destory both cookies that get created.
delete $cookies["access_token"];
delete $cookies["accessToken"];
//Perform the Passport Logout
$http.post('/auth/logout');
});
self.currentUser = null;
cb();
},
ensureHasCurrentUser: function (cb) {
if ((!this.currentUser || this.currentUser.id === 'social') && $cookies.accessToken) {
LoopBackAuth.currentUserId = LoopBackAuth.accessTokenId = null;
$http.get('/auth/current')
.then(function (response) {
if (response.data.id) {
LoopBackAuth.currentUserId = response.data.id;
LoopBackAuth.accessTokenId = $cookies.accessToken.substring(
2, 66);
}
if (LoopBackAuth.currentUserId === null) {
delete $cookies['accessToken'];
LoopBackAuth.accessTokenId = null;
}
LoopBackAuth.save();
self.currentUser = response.data;
var profile = self.currentUser && self.currentUser.profiles &&
self.currentUser.profiles.length && self.currentUser.profiles[
0];
if (profile) {
self.currentUser.name = profile.profile.name;
}
cb(self.currentUser);
}, function () {
console.log('User.getCurrent() err', arguments);
LoopBackAuth.currentUserId = LoopBackAuth.accessTokenId =
null;
LoopBackAuth.save();
cb({});
});
} else {
if(self.currentUser){
console.log('Using cached current user.');
}
cb(self.currentUser);
}
}
};
return self;
});
})();
and then in my routes file I am doing -
$stateProvider
.state('router', {
url: '/router',
template: '<div class="lockscreen" style="height: 100%"></div>',
controller: 'RouteCtrl'
})
.state('error', {
url: '/error',
template: '<div class="text-center alert alert-danger" style="margin: 100px">An error occurred.</div>'
})
.state('app', {
abstract: true,
url: '/app',
templateUrl: 'modules/core/views/app.html',
controller: 'MainCtrl',
data: {
permissions: {
only: ['admin', 'student']
}
}
})
.state('app.home', {
url: '',
templateUrl: 'modules/core/views/home.html',
controller: 'HomeCtrl',
data: {
permissions: {
only: ['admin', 'student']
}
}
})
.state('tutor', {
abstract: true,
url: '/tutor',
templateUrl: 'modules/core/views/app.html',
controller: 'MainCtrl',
data: {
permissions: {
only: ['admin', 'tutor']
}
}
})
.state('tutor.home', {
url: '',
templateUrl: 'modules/core/views/home.html',
controller: 'HomeCtrl',
data: {
permissions: {
only: ['admin', 'tutor']
}
}
});
$urlRouterProvider.otherwise('/router');
but now I am getting the following error in the browser console -
Error: undefined role or invalid role validation
at Object.Permission._findMatchingRole (angular-permission.js:170)
at Object.Permission.resolveIfMatch (angular-permission.js:211)
at Object.Permission.authorize (angular-permission.js:239)
at angular-permission.js:45
at Scope.$broadcast (angular-scenario.js:24081)
at Object.transitionTo (angular-ui-router.js:3229)
at Array.<anonymous> (angular-ui-router.js:2346)
at Object.invoke (angular.js:4185)
at handleIfMatch (angular-ui-router.js:1836)
at angular-ui-router.js:1891
so how can I debug this error or implement client side role based authorization in my loopback app
[..] implement client side role based authorization in my loopback app
This doesn't mean anything, loopback is your server application.
Client-side authorization should be prohibited, since clients can be tampered with.
Authorization should take place server-side exclusively. Client-side you should just adapt the content in function of the role. That way if someone tampers with your client code at least its http requests to the API will fail and your data is safe

Error handling when data is not resolved in Angular UI router

I am using angular-ui-router's resolve to get data from server before moving a state. I want to inform user if the request has failed. I have service that will response error the request has failed. My question is how can I detect the failure in ui-router resolve and trigger some Modal service like pop up.
I have read some related posts online, but I am still confused how to make it happen. Thanks in advanced!
Config and Service:
angular.module('myApp',['ui.router', 'ngAnimate', 'ui.bootstrap'])
.config(function ($stateProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$stateProvider
.state('customer', {
url: '/customer',
templateUrl: '/customer.html',
controller: 'CustomerCtrl',
resolve: {
/*
* How to inject CustomerService here
* How to catch the server error
* How to trigger a popup
*/
data: cusomter_data
}
});
})
.service('CustomerService', function($http, $q) {
return ({
getGeneral: getGeneral
});
function getGeneral(customer_id) {
var request = $http({
method: "get",
url: '/customer',
params: {
customer_id: customer_id
}
});
return (request.then( handleSuccess, handleError));
}
function handleError (response){
if (!angular.isObject(response.data) || !response.data.message) {
return($q.reject("Failed to retrieve customer information."));
}
return($q.reject(response.data.message));
}
function handleSuccess(response) {
return (response.data);
}
});
After some research, I found out a solution by creating a errorModal service and inject it to resolve. Here is my solution.
$stateProvider
.state('customer', {
url: '/customer',
templateUrl: '/customer.html',
controller: 'CustomerCtrl',
resolve: {
data: function(CustomerService, SelectedCustomerService, errorModalService) {
var shared = SelectedCustomerService;
return CustomerService.getData(shared.customerid).then(
function (data) { return data; },
function(error) {
var modalOptions = {
closeButtonText: 'Close',
headerText: 'Customer Error',
bodyText: error
};
errorModalService.showModal({}, modalOptions);
}
);
}
}
});

Child View/Route that Resolves from Different Service than Parent

I'm having an issue loading a child view/route while resolving a GET from a different service from the parent view/route.
Within the parent view, each ion-item links to /#/tab/categories/{{ category.listing_category_id }}
When clicked the URL populates (for a flash) with the correct category ID, the child's service successfully receives the category ID, runs the subsequent GET request & returns the data as a promise...that all works as intended. The issue is that the child view/route never loads. All help/guidance is very much appreciated.
Parent
angular.module('rainbowPages.tab.categories', [])
.config(function($stateProvider, $urlRouterProvider) {
// UI Router
$stateProvider.state('tab.categories', {
url: '/categories',
views: {
'tab-categories': {
templateUrl: 'views/tab-categories/tab-categories.html',
controller: 'CategoriesCtrl'
}
}
});
// otherwise
$urlRouterProvider.otherwise('/tab/categories');
})
.factory('CategoriesService', function($resource) {
var remoteCategoriesURL = 'http://104.167.104.163:7000/api/v1/categories',
categoriesService = $resource(remoteCategoriesURL, {}, {
getAll: {
method: 'GET',
isArray: true
}
});
return categoriesService;
})
.controller('CategoriesCtrl', function($scope, CategoriesService) {
$scope.categories = CategoriesService.getAll();
});
Child
angular.module('rainbowPages.tab.categories.detail', [])
.config(function($stateProvider, $urlRouterProvider) {
// UI Router
$stateProvider.state('tab.category-detail', {
url: '/categories/:listing_category_id',
views: {
'tab-categories': {
templateUrl: 'views/category-detail/category-detail.html',
controller: 'categoryDetailCtrl'
}
},
resolve: {
listings: function($stateParams, CategoryDetailService) {
// bind data to listing
return CategoryDetailService($stateParams.listing_category_id);
}
}
});
})
.factory('CategoryDetailService', function($resource) {
var remoteCategoryURL = 'http://104.167.104.163:7000/api/v1/category/:categoryID',
categoryDetailService = $resource(remoteCategoryURL, {categoryID:'#listing_category_id'}, {
get: {
method: 'GET',
isArray: true
}
}),
getListingsInCategory = function getListingsInCategory(categoryID) {
listingsInCategory = categoryDetailService.get({categoryID:categoryID}, function(promise) {
if(promise.$resolved = true) {
console.log(promise); // how I know the promise has the correct data
return promise;
}
});
};
return getListingsInCategory;
})
.controller('categoryDetailCtrl', function($scope, listings){
console.log('listings are : ' + listings);
$scope.listings = listings;
});

Resources