Factory and Resource Makes Angular UI Router not Work - javascript

I've been following this tutorial https://www.youtube.com/watch?v=X_NZr_-RaLw and in my clientapp.js, when I insert
.factory('UserService', function($resource) {
return $resource('https://troop.tech/api/users/:user', {user: '#user'});
});
Into my code, all the angular UI routing just stops working.
Context:
var myApp = angular.module('myApp', ['ui.router','ngRouter'])
myApp.factory('UserService', function($resource) {
return $resource('https://troop.tech/api/users/:user', {user: '#user'});
});
myApp.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise('/dashboard');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'partial-home.html'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'partial-dashboard.html'
})
.state('about', {
url: '/about',
templateUrl: 'partial-about.html'
})
.state('register', {
url: '/register',
templateUrl: 'partial-register.html'
});
$httpProvider.interceptors.push('authInterceptor');
});
myApp.controller('userController', function ($scope, $http, $window, UserService) {
$scope.users = UserService.query();
$scope.setDataForUser = function(userID) {
};
$scope.addUser = function(){
};
...

In your factroy you use $resource as a parameter so you need inject angular built in resource liberary.
In index.html:
<script src="yourComponentFolder/angular-resource/angular-resource.js"></script>
And add a module ngResource...
var myApp = angular.module('myApp', ['ui.router','ngRouter','ngResource']);
Reference in your Application that yoy follow
And one thing if you use ui-router not necessary to inject ngRouter so if you can discard ngRouter from module.

Related

Angularjs routing template is not displayed

I have the following app.js file:
'use strict';
var app = angular.module('app', [
'auth0',
'angular-storage',
'angular-jwt',
'ui.router',
'Environment',
'Api',
'Profile'
]);
app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'js/modules/App/views/frontpage.html'
})
.state('login', {
url: '/login',
templateUrl: 'js/modules/User/views/login.html',
controller: 'LoginCtrl'
});
$urlRouterProvider
.otherwise('/main');
}]);
app.config(['authProvider', '$httpProvider', '$locationProvider', 'jwtInterceptorProvider',
function myAppConfig(authProvider, $httpProvider, $locationProvider, jwtInterceptorProvider) {
authProvider.init({
domain: 'marcrasmussen.eu.auth0.com',
clientID: 'hphpe4JiceMW8FSA02CN7yOYl5fUaULe',
loginUrl: '/login'
});
authProvider.on('loginSuccess', ['$location', 'profilePromise', 'idToken', 'store',
function ($location, profilePromise, idToken, store) {
console.log("Login Success");
profilePromise.then(function (profile) {
store.set('profile', profile);
store.set('token', idToken);
});
$location.path('/');
}]);
//Called when login fails
authProvider.on('loginFailure', function () {
alert("Error");
});
//Angular HTTP Interceptor function
jwtInterceptorProvider.tokenGetter = ['store', function (store) {
return store.get('token');
}];
//Push interceptor function to $httpProvider's interceptors
$httpProvider.interceptors.push('jwtInterceptor');
}]);
app.run(['auth', function (auth) {
// This hooks all auth events to check everything as soon as the app starts
auth.hookEvents();
}]);
And i have the following profile.js file:
angular.module('Profile', [])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('profile', {
abstract: true,
url: '/profile'
})
.state('profile.index', {
url: '/index',
templateUrl: 'js/modules/Profile/views/viewProfile.html'
})
}]);
in my index.html the files are listed as such:
<script src="js/modules/Profile/lib/profile.js"></script>
<script src="js/modules/App/lib/app.js"></script>
<script src="js/modules/App/directives/login/login.js"></script>
And lastly ofcourse i have my view port:
<div class="main" ui-view>
</div>
As you can tell my application starts on the route /main this works perfectly fine and frontpage.html is being rendered with all the html inside that file.
However when i go to profile.index or /profile/index no error is displayed in the console and no html within the template file js/modules/Profile/views/viewProfile.html is displayed.
Can anyone tell me why this is happening? what am i doing wrong?
I think the issue may be your abstract state. You are not defining a template or templateUrl for this state. Also note that the template for your abstract state must include a ui-view directive in order for its children to populate.
https://github.com/angular-ui/ui-router/wiki/nested-states-%26-nested-views#abstract-state-usage-examples
You may need to do something along the lines of:
.state('profile', {
abstract: true,
url: '/profile',
template: '<ui-view />
})

In Angular ui-router, for nested state, corresponding template is not rendering?

I want to show tab(profile+setting), like the following image, but when i click on any tabs, corresponding template is not loading. In customerinfo.view.html I tried to change <div ui-view="{{tab.view}}"></div> to <div ui-view></div> it causing me infinite digest cycle.
I am able to change the url, When first time we hit the url http://localhost:3000/home/#/updatecustomer/3/ following time opens, when click on profile, url change to http://localhost:3000/home/#/updatecustomer/3/profile, but corresponding template(profile.html) is not loading, same is happening for setting
I go through this stackoverflow question, but no help
Module definition
(function() {
'use strict';
var app = angular.module('app', ['ui.router', 'ngCookies', 'ui.bootstrap']);
app.config(function config($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/',
controller: 'HomeController',
templateUrl: 'home/home.view.html',
})
.state('home.updatecustomer', {
url: 'updatecustomer/:customerId/',
controller: 'TabsDemoCtrl',
templateUrl: 'addcustomer/customerinfo.view.html',
})
.state('home.updatecustomer.profile', {
url: 'profile',
controller: 'ProfileCtrl',
templateUrl: 'addcustomer/profile.html',
}))
.state('home.updatecustomer.setting', {
url: 'setting',
controller: 'SettingCtrl',
templateUrl: 'addcustomer/setting.html',
})
customer.js
(function () {
'use strict';
var app = angular.module('app');
app.controller('TabsDemoCtrl', TabsDemoCtrl);
TabsDemoCtrl.$inject = ['$scope', '$state'];
function TabsDemoCtrl($scope, $state){
$scope.customer = 3;
$scope.tabs = [
{ title:'profile', view:'profile', active:true },
{ title:'setting', view:'setting', active:false }
];
}
})();
customerinfo.view.html
<uib-tabset active="active">
<uib-tab ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active" disable="tab.disabled">
<div ui-view="{{tab.view}}"></div>
</uib-tab>
</uib-tabset>
profile.js
(function () {
'use strict';
var app = angular.module('app') ;
app.controller('ProfileCtrl', ProfileCtrl);
ProfileCtrl.$inject = ['$scope'];
function ProfileCtrl($scope){
$scope.profile="Profile 123";
}
})() ;
profile.html
profile
Setting.js
(function () {
'use strict';
var app = angular.module('app') ;
app.controller('SettingCtrl', SettingCtrl);
SettingCtrl.$inject = ['$scope'];
function SettingCtrl($scope){
$scope.setting="setting 1213";
}
})() ;
setting.html
setting
Edit:
1) The first thing-- the naming of your urls. Instead of http://localhost:3000/home/#/updatecustomer/3/ the url should be http://localhost:3000/#/updatecustomer/3/
2) You want the tabs to be children of your home state. Do this by setting abstract: true.
$stateProvider
.state('home', {
abstract: true,
controller: 'HomeController',
templateUrl: 'home/home.view.html'
})
3) The url for your routes must begin with a /.
.state('home.your-splash-view', {
url: '/home',
controller: 'HomeCtrl',
templateUrl: 'home/splash.view.html'
})
.state('home.updatecustomer', {
url: '/updatecustomer/:customerId/',
controller: 'TabsDemoCtrl',
templateUrl: 'addcustomer/customerinfo.view.html'
})
.state('home.updatecustomer.profile', {
url: '/profile',
controller: 'ProfileCtrl',
templateUrl: 'addcustomer/profile.html'
});
4) Consider navigating states with theui-sref directive.
Something like:
<uib-tab ui-sref='home.updatecustomer.profile'> ... </ui-tab>
Related:
what is the purpose of use abstract state?
Why give an "abstract: true" state a url?

Implementing secure pages and $rootScope is not defined

Inside my angularjs app. I have userService which has method for determination if user is loggedIn or not. userService.user.loggedIn()
now I want to use that service in order to implement secure pages, where I will redirect user upon this userService.user.loggedIn() statement.
my app.js looks like this
(function () {
"use strict";
var app = angular.module("myApp",
["common.services",
"$rootScope",
"ui.router",
"ui.mask",
"userService",
"ui.bootstrap"]);
app.config(["$stateProvider", "$urlRouterProvider",
function ($stateProvider, $urlRouterProvider, $rootScope) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state("index", {
url: "/",
templateUrl: "app/index.html",
})
// Home page /* SECURED */
.state("home", {
url: "/home",
templateUrl: "app/home/home.html",
controller: "HomeController as vm",
data: {
requiresLogin: true
}
})
// Login
.state("login", {
url: "/login",
templateUrl: "app/login/login.html",
controller: "LoginController as vm"
})
}]
);
$rootScope.$on('$stateChangeStart', function (e, to, userService) {
if (to.data && to.data.requiresLogin) {
if (!userService.user.loggedIn()) {
//token not found/not valid
e.preventDefault();
$location.path('/login');
}
}
});
}());
Inside console I'm getting
ReferenceError: $rootScope is not defined
$rootScope.$on('$stateChangeStart', function (e, to, appUserService,
$rootScope)...
It's not in the array of injectable:
Try this:
app.config(["$stateProvider", "$urlRouterProvider", "$rootScope",
function ($stateProvider, $urlRouterProvider, $rootScope) {
You can only place providers in config. So place your $rootScope.$on function in app controller.

dynamic templateUrl with param using angular-ui-router

I have a route to handle creation, modification, view and list of users like this :
angular
.module('abcApp', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('user.add', {
url: '/mgt/user/add',
templateUrl: 'views/mgt_user/add.html',
controller: 'MgtUserCtrl'
})
.state('user.view', {
url: '/mgt/user/view/:userId',
templateUrl: 'views/mgt_user/view.html',
controller: 'MgtUserCtrl'
})
.state('user.list', {
url: '/mgt/user/list',
templateUrl: 'views/mgt_user/list.html',
controller: 'MgtUserCtrl'
});
});
I want to use one route where I can pass the mode as param and get the right templateUrl:
angular
.module('abcApp', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('userMangement', {
url: '/mgt/user/:mode/:userId',
templateUrl: 'views/mgt_user/' + $routeParams.mode + '.html',
controller: 'MgtUserCtrl'
});
});
mode can be : view, edit, list.
Is there a way to do this?
You can use templateProvider.
$stateProvider
.state('userManagement', {
url: '/mgt/user/:mode/:userId',
controller: 'MgtUserCtrl',
templateProvider: ['$route', '$templateCache', '$http', function($route, $templateCache, $http) {
var url = '/views/mgt_user/' + $route.current.params.mode + '.html';
$http.get(url, {cache: $templateCache}).then(function(html) {
return html;
});
}]
})
You cannot use $routeparams here becuase $routeParams is available after $routeChangeSuccess event.

Setting file path and organizing the code in Angularjs

Hi I have following module, route and controller defined in one file called main.js
var mainApp = angular.module("mainApp", ["ngRoute", "ngResource", "ui"]).
config(function ($routeProvider) {
$routeProvider.
when('/addEmp', { controller: EmpCtrl, templateUrl: 'addEmp.html' }).
when('/addLoc', { controller: LocCtrl, templateUrl: 'newLocation.html' }).
otherwise({ redirectTo: '/' });
});
mainApp.factory("addEmp", ['$resource', function ($resource) {
return $resource('/api/addEmp/:id', { id: '#id' }, { update: { method: 'PUT' } });
}]);
mainApp.factory("addLoc", ['$resource', function ($resource) {
return $resource('/api/newLoc/:id', { id: '#id' }, { update: { method: 'PUT' } });
}]);
//Controllers
var EmpCtrl = function ($scope, $location, addEmp) {
//code here
};
var LocCtrl = function ($scope, $location, newLocation) {
//code here
};
What I am trying to do is organize this one file code into different files. I created script/controller folder where I want to have individual files for controller like
EmpCtrl.js and LocCtrl.js.
When I created the controller files and copied the controller code in it i get error of EmptCtrl and LocCtrl not defined.
Can you please tell me how I can set it up in different folders with appropriate path settings?
Thanks
try this
angular.module("mainApp", ["ngRoute", "ngResource", "ui"]).
config(function ($routeProvider) {
$routeProvider.
when('/addEmp', { controller: 'empCtrl', templateUrl: 'addEmp.html' }).
when('/addLoc', { controller: 'locCtrl', templateUrl: 'newLocation.html' }).
otherwise({ redirectTo: '/' });
});
//in empCtrl.js file
angular.module('mainApp').controller('empCtrl', ['$scope', '$location', 'addEmp',
function ($scope, $location, addEmp) {
//code here
}]);
// same for locCtrl
In your html make sure to include your mainApp.js file before you empCtrl and locCtrl scripts
the key is that you use string names to refer to your controller in your rout configs
{ controller: 'empCtrl' ... }
instead of
{ controller: EmpCtrl ... }
I would recommend that you use require.js to modularize your Angular project, you won't have to worry about order of script includes and it will result in a cleaner project

Categories

Resources