Cannot read property 'index' of undefined - javascript

I am very new to Angular and was trying to use it on my Rails Application. But I got the following error.
TypeError: Cannot read property 'index' of undefined
app.js code
angular.module('ticket', ['ngResource', 'ui.router', 'templates'])
.controller('AppCtrl', ['$rootScope', function($rootScope) {
var _this = this;
return $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
return $rootScope.pageTitle = $route.current.title;
});
}])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/_home.html',
controller: 'MainCtrl'
})
.state('members', {
url: '/members',
templateUrl: 'members/_members.html',
controller: 'MemberCtrl'
})
.state('guards', {
url: '/guards',
templateUrl: 'guards/_guards.html',
controller: 'GuardCtrl'
})
.state('tickets', {
url: '/tickets',
templateUrl: 'tickets/_tickets.html',
controller: 'TicketCtrl'
});
$urlRouterProvider.otherwise('home')
}]);
memberCtrl.js code (inside members directory)
angular.module('ticket')
.factory('Member', ['$resource', function($resource) {
return $resource("/members/:id", {id: "#id"}, {
get: { method: 'GET'},
save: { method: 'POST'},
index: { method: 'GET', isArray: true},
remove: { method: 'DELETE'},
"delete": { method: 'DELETE'},
update: { method: 'PUT'}
});
}])
.controller('MemberCtrl', ['$scope', function($scope, Member) {
console.log(Member.index());
$scope.members = Member.index();
}]);

You need to inject dependency Member in the controller properly.
.controller('MemberCtrl', ['$scope', 'Member', function($scope, Member) {
//^^^^^^^^^^
instead of
.controller('MemberCtrl', ['$scope', function($scope, Member) {

Related

How to prevent user logging out when refreshing the page in an Angular(Client) and Loopback(Server) application?

I have a Loopback.io SPA with an Angular client. I followed the official Loopback Documentation https://loopback.io/doc/en/lb2/Create-AngularJS-client.html
The problem is that when I refresh the page in the browser, the client is logging out. It seems that the currentUser variable is not restored after the refresh. How could I solve this?
Here are the auth.js and app.js files:
js/services/auth.js
angular
.module('app')
.factory('AuthService', ['Reviewer', '$q', '$rootScope', function(User, $q,
$rootScope) {
function login(email, password) {
return User
.login({
email: email,
password: password
})
.$promise
.then(function(response) {
$rootScope.currentUser = {
id: response.user.id,
tokenId: response.id,
email: email
};
});
}
function logout() {
return User
.logout()
.$promise
.then(function() {
$rootScope.currentUser = null;
});
}
function register(email, password) {
return User
.create({
email: email,
password: password
})
.$promise;
}
return {
login: login,
logout: logout,
register: register
};
}]);
client/js/app.js
angular
.module('app', [
'ui.router',
'lbServices'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider
.state('add-review', {
url: '/add-review',
templateUrl: 'views/review-form.html',
controller: 'AddReviewController',
authenticate: true
})
.state('all-reviews', {
url: '/all-reviews',
templateUrl: 'views/all-reviews.html',
controller: 'AllReviewsController'
})
.state('edit-review', {
url: '/edit-review/:id',
templateUrl: 'views/review-form.html',
controller: 'EditReviewController',
authenticate: true
})
.state('delete-review', {
url: '/delete-review/:id',
controller: 'DeleteReviewController',
authenticate: true
})
.state('forbidden', {
url: '/forbidden',
templateUrl: 'views/forbidden.html',
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'AuthLoginController'
})
.state('logout', {
url: '/logout',
controller: 'AuthLogoutController'
})
.state('my-reviews', {
url: '/my-reviews',
templateUrl: 'views/my-reviews.html',
controller: 'MyReviewsController',
authenticate: true
})
.state('sign-up', {
url: '/sign-up',
templateUrl: 'views/sign-up-form.html',
controller: 'SignUpController',
})
.state('sign-up-success', {
url: '/sign-up/success',
templateUrl: 'views/sign-up-success.html'
});
$urlRouterProvider.otherwise('all-reviews');
}])
.run(['$rootScope', '$state', function($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function(event, next) {
// redirect to login page if not logged in
if (next.authenticate && !$rootScope.currentUser) {
event.preventDefault(); //prevent current page from loading
$state.go('forbidden');
}
});
}]);
scope in angularjs after refresh page initial, and not save old value before refresh
you can save token in local storage browser (or cookie) and in load page set scope

AngularJs call controller function from factory

I'm trying a sample with angularJs where I'm trying to call a factory method and in the factory method, I'm doing an ajax callback to get result from database and in the success event of the ajax callback, I need to call a function in the controller to bind the result to the UI.
My Angular Code:
angular.module('myApp.controllers', [])
.controller('TasksListCtrl', ['$scope', '$rootScope', '$routeParams', 'Task',
function($scope, $rootScope, $routeParams, Task) {
debugger;
//factory call
Task.query({
MobileNumber: $routeParams.MobileNumber,
ClientCode: $routeParams.ClientCode
});
$rootScope.UserMobileNumber = $routeParams.MobileNumber;
$scope.BindTasksList = function(resultData) {
debugger;
$scope.Tasks = resultData;
$scope.$apply();
}
}
]);
My Angular Factory Code:
'use strict';
(function() {
function GetTasks(MobileNumber, ClientCode) {
debugger;
$.ajax({
url: '/api/TasksAPI/GetTasksList',
type: 'GET',
datatype: 'json',
data: {
'MobileNumber': MobileNumber,
'ClientCode': ClientCode
},
success: function(response) {
debugger;
$scope.BindTasksList(response);
},
error: function(xhr) {}
});
};
angular.module('myApp.DbScripts', [])
.factory('Task', [
function() {
return {
query: function(data) {
debugger;
GetTasks(data.MobileNumber, data.ClientCode);
}
}
}
]);
}());
My app.js Code:
'use strict';
angular.module('myApp', [
'ngTouch',
'ngRoute',
'ngAnimate',
'myApp.controllers',
'myApp.DbScripts'
]).
config(['$routeProvider',
function($routeProvider) {
debugger;
$routeProvider.when('/tasks/:MobileNumber/:ClientCode', {
templateUrl: 'partials/tasks-list.html',
controller: 'TasksListCtrl'
});
$routeProvider.when('/tasks/:taskId', {
templateUrl: 'partials/task-details.html',
controller: 'TaskDetailCtrl'
});
$routeProvider.when('/tasks/:taskId/status', {
templateUrl: 'partials/task-completion-details.html',
controller: 'TaskCompletionDetailCtrl'
});
$routeProvider.when('/tasks/:taskId/route', {
templateUrl: 'partials/route-details.html',
controller: 'RouteDetailCtrl'
});
$routeProvider.otherwise({
redirectTo: '/tasks'
});
}
]);
But, I'm unable to call the function in controller. I've also tried it with angular.element(document.getElementById('TasksListCtrl')).scope().BindTasksList(response). But even that's not working.
Can anyone please point out the mistake I'm doing?
How to send the $scope of the controller to the factory?
You can do this by leveraging the $http promises, in you factory, return the promise instead as follows
'use strict';
(function() {
function GetTasks(MobileNumber, ClientCode) {
};
angular.module('myApp.DbScripts', [])
.factory('Task', [
function($http) {
return {
query: function(data) {
return $http({
url: '/api/TasksAPI/GetTasksList',
method: 'GET',
params: {
'MobileNumber': data.MobileNumber,
'ClientCode': data.ClientCode
}
}).then(function(result) {
return result;
});
}
}
}
]);
}());
Then in your controller you can access the $http response object that is returned:
//factory call
Task.query({
MobileNumber: $routeParams.MobileNumber,
ClientCode: $routeParams.ClientCode
}).then(function(resp) {
// access $http resp here and attach to $scope.Tasks
});
If you can, I would advocate using $q along $http as well, so that you do not need to parse through the http response and get a nice little response data object back
plnk

Unknown Provider error despite other controllers and services working

This is what my app.js looks like where I have defined the states, controller and urls for all the templates:
angular.module('starter', ['ionic', 'starter.controllers','starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
ionic.Platform.fullScreen()
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
// StatusBar.styleDefault();
StatusBar.hide();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/rubyonic/menu.html",
controller: 'AppCtrl',
reload: true
})
// .state('login', {
// url: "/login",
// templateUrl: "templates/rubyonic/login.html",
// controller: 'AppCtrl'
// })
.state('login', {
url: '/login',
templateUrl: "templates/rubyonic/login.html",
controller: 'LoginCtrl'
})
.state('app.alerts', {
url: "/alerts",
views: {
'menuContent': {
templateUrl: "templates/rubyonic/alerts.html",
controller: 'AppCtrl'
}
}
})
.state('app.studies', {
url: "/studies",
views: {
'menuContent': {
templateUrl: "templates/rubyonic/studies.html",
controller: 'AppCtrl',
reload: true
}
}
})
.state('app.study_collections', {
url: "/studies/:studynodeRef",
views: {
'menuContent': {
templateUrl: "templates/rubyonic/overview.html",
controller: 'AppCtrl',
reload: true
}
}
})
.state('app.rank-charts', {
url: "/rank_charts",
views: {
'menuContent': {
templateUrl: "templates/rubyonic/rank_charts.html",
controller: 'AppCtrl'
}
}
})
// .state('app.overview', {
// url: "/overview",
// views: {
// 'menuContent': {
// templateUrl: "templates/rubyonic/overview.html"
// }
// }
// })
.state('app.claim-details', {
url: "/claim-details",
views: {
'menuContent': {
templateUrl: "templates/rubyonic/claim_details.html",
controller: 'AppCtrl'
}
}
})
.state('app.scorecards', {
url: "/scorecards",
views: {
'menuContent': {
templateUrl: "templates/rubyonic/scorecards.html",
controller: 'AppCtrl'
}
}
})
.state('app.fnol', {
url: "/fnol",
views: {
'menuContent': {
templateUrl: "templates/rubyonic/fnol.html",
controller: 'AppCtrl'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
})
Here is my Login Controller:
angular.module('starter.controllers', ['highcharts-ng'])
.controller('LoginCtrl', ['$scope','$stateProvider','UserService', function($scope,$stateProvider,UserService) {
$scope.credentials = {
username: localStorage.getItem('username') || '',
password: localStorage.getItem('password') || ''
};
$scope.login = function(credentails) {
UserService.login(credentails).then(function(user) {
$scope.loginMessage = false;
localStorage.setItem('username', $scope.credentials.username);
localStorage.setItem('password', $scope.credentials.password);
$state.go('app.studies') ;
}
,
function(data) {
$scope.loginMessage = 'Username/Password Invalid';
}
);
}
if($scope.credentials.username && $scope.credentials.password){
$scope.login($scope.credentials);
}
}])
and here is my UserService which is injected into the login controller:
angular.module('starter.services', [])
.factory('UserService', ['$rootScope', '$q', '$http', function($rootScope, $q, $http) {
return {
login: function(credentails) {
var deffered = $q.defer();
$http({
method: 'post',
url: 'http://localhost/platform/j_spring_security_check',
params: {
'j_username': credentails.username,
'j_password': credentails.password
}
}).success(function(user, status, headers, config) {
userLoggedIn = true;
// $location.path('#/app/studies');
localStorage.setItem('lastLoginTime', new Date().getTime());
$rootScope.$broadcast('USER_LOGIN_SUCCESS');
deffered.resolve(user);
}).error(function(data, status, headers, config){
$rootScope.$broadcast('USER_LOGIN_FAILED');
deffered.reject(data);
});
return deffered.promise;
},
isUserLoggedIn: function() {
return userLoggedIn;
}
};
}])
When I run my app I get the: Error: [$injector:unpr] Unknown provider: $stateProviderProvider <- $stateProvider <- LoginCtrl in my console. I know my controller and services are setup correctly because the other templates along with their controllers work. I would really appreciate if someone could help me fix this.
The reason behind you are getting error is, inside LoginCtrl you are trying to inject the Provider which is $stateProvider, Basically provider are not available inside the controller, They are accessible as service name,If would be $state instead of $stateProvider inside your controller
controller('LoginCtrl', ['$scope','$stateProvider','UserService',
Should be
controller('LoginCtrl', ['$scope','$state','UserService',

ng-click change route in angularjs with param

I would like to change the route of an angularjs application build with ionic framework, but the route didn't change
this is my code of app.js
angular.module('starter', ['ionic', 'starter.controllers'])
.state('app.annuaire.menuitempage', {
url: "/menuitempage/:ID",
views: {
'menuContent' :{
templateUrl: "templates/menuItemPage.html",
controller: function($stateParams){
$stateParams.ID ;
}
}
}
})
.state('app.annuaire', {
url: "/annuaire",
views: {
'menuContent' :{
templateUrl: "templates/annuaire.html",
controller: 'MenuItemCtrl'
}
}
})
And this is the code of my controller
angular.module('starter.controllers', [])
.controller('MenuItemCtrl', function($scope, $http, $location) {
$scope.itemsMenu = {};
var responsePromise = $http.get("http://monguidepratique.com/mobile/getCategories.php?parent_id=0");
responsePromise.success(function(data, status, headers, config) {
//alert(data);
$scope.itemsMenu = data;
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
$scope.itemClick = function(path){
alert(1);
$location.path(path);
};
})
And this is my html code in annuaire.html
<div class="col" ng-click="itemClick('/menuitempage/1628')"><img class="img_menu" src="img/home.png"><p class="titre_center">Accueil</p></div>
Try
$location.path(path)
instead of
$state.go(path)
You need to inject $location service into your controller.
Edit
If you are using $state.go - you should to use it next way:
$scope.itemClick = function(id){
$state.go('app.annuaire.menuitempage', {'ID': id})
};
And HTML:
<div class="col" ng-click="itemClick(1628)"><img class="img_menu" src="img/home.png"><p class="titre_center">Accueil</p></div>
The first param is state name, not URL, the second is an Object with your params.
I solved my problem
in annuaire.html i changed
itemClick('/menuitempage/1628')
by
itemClick('/app/menuitempage/1628')
and i changed the route name app.annuaire.menuitempage by
app.menuitempage
.state('app.menuitempage', {
url: "/menuitempage/:ID",
views: {
'menuContent' :{
templateUrl: "templates/menuitempage.html",
controller: 'SubMenuCtrl'
}
}
})

Having trouble with AngularJS routeparams (stateparams)

i am having trouble with the following route for the albums. below is my controller and the routes file, i am using the angular ui module. i am trying to load the photos on the album on the /photos/:albumId route.
tripApp.controller('HotelPhotoAlbumController', function($scope, $timeout, Hotel, $stateParams, $http) {
$scope.hotelId = $stateParams.hotelId;
$scope.albumId = $stateParams.albumId;
$http({
method: 'GET', url: 'hotels/' + $scope.hotelId + '/albums/' + $scope.albumId + '.json'
}).success(function(data, status, headers, config){
$scope.photos = data;
}).error(function(data, status, headers, config){
$scope.status = status;
});
});
var tripApp = angular.module('tripApp', ['ui.state', 'ui.bootstrap', 'ui.calendar', 'ui.map', 'infinite-scroll', 'tripApp.directives', 'hotelServices', 'ngSanitize'])
tripApp
.value('$anchorScroll', angular.noop)
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/hotels")
$stateProvider
.state('hotels', {
url: "/hotels",
templateUrl: "templates/hotels.html",
controller: "HotelsController"
})
.state("hotels.search", {
url: "/search",
templateUrl: "templates/hotels.search.html",
controller: "HotelsController"
})
.state("hotel", {
url: "/:hotelId",
templateUrl: "templates/hotel.html",
controller: "HotelDetailController"
})
.state("hotel.index", {
url: "/",
templateUrl: "templates/hotel.home.html",
controller: "HotelDetailController"
})
.state("hotel.options", {
url: "/options",
templateUrl: "templates/hotel.options.html",
controller: "HotelRoomsController"
})
.state("hotel.reviews", {
url: "/reviews",
templateUrl: "templates/hotel.reviews.html",
controller: "HotelDetailController"
})
.state("hotel.photos", {
url: "/photos",
templateUrl: "templates/hotel.photos.html",
controller: "HotelDetailController"
})
.state("hotel.photos.details", {
url: "/photos/:albumId",
templateUrl: "templates/hotel.photos.details.html",
controller: "HotelPhotoAlbumController"
})
.state("hotel.calendar", {
url: "/calendar",
templateUrl: "templates/hotel.calendar.html",
controller: "HotelCalendarController"
})
.state("restaurants", {
url: "/restaurants",
templateUrl: "templates/restaurants.html",
controller: "RestaurantsController"
})
})
State url declaration is relative to the parent so instead of "/photos/:albumId" try "/:albumId".

Categories

Resources