run function and location path issue - angularjs

I'm using a run function to conditionally redirect people to a page , regarding their login state. redirection depending on user state works pretty well , but after the redirection , navigate between page won't work , when i click to navigate i stay in the same page. this is what my code looks like , can anyone help me?
var app = angular.module( 'YourApp', [ 'ngMaterial', "ngRoute" ])
app.config(($routeProvider, $mdThemingProvider, $mdIconProvider, $mdDateLocaleProvider) => {
$mdIconProvider
.iconSet("lala", 'assets/logo/ic_keyboard_arrow_left_white_48px.svg', 24)
.iconSet("social", 'img/icons/sets/social-icons.svg', 24);
$mdThemingProvider.theme('primary')
.primaryPalette('brown')
.accentPalette('yellow');
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
};
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "myCtrl"
}).when("/voyages", {
templateUrl: "voyages.html",
controller: "voyageCtrl"
}).when("/bagages", {
templateUrl: "bagages.html",
controller: "BagagesCtrl"
}).when("/login",{
templateUrl: "login.html",
controller: "loginCrtl"
}).when("/voyageID/:voyageid" , {
templateUrl: "voyageID.html",
controller: "voyageIDCtrl"
})
.otherwise({
redirectTo: '/'
});
})
.run(function($rootScope, $location) {
var Parse = require('parse');
Parse.initialize("CODE", "PIN");
Parse.serverURL = 'https://stelimac.herokuapp.com/parse';
$rootScope.$on("$routeChangeStart", (event) => {
var currentUser = Parse.User.current();
if (!currentUser) {
$location.path("/login")
} else {
$location.path("/")
}
})
});

change $location.path to $state.go
.run(function($rootScope, $state) {
var Parse = require('parse');
Parse.initialize("CODE", "PIN");
Parse.serverURL = 'https://stelimac.herokuapp.com/parse';
$rootScope.$on("$routeChangeStart", (event) => {
var currentUser = Parse.User.current();
if (!currentUser) {
$state.go("/login")
} else {
$state.go("/")
}
})
});

Related

Angular Routing and Binding data from controller

I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}

Stop routing on click event in template in angularjs

This is my angularjs app
var appblog = angular.module('Blogmain', ['ngRoute', 'ngSanitize']);
appblog
.config(['$routeProvider', function ($routeProvider) {
debugger;
//Setup routes to load partial templates from server. TemplateUrl is the location for the server view (Razor .cshtml view)
$routeProvider
.when('/Blog/Index', { templateUrl: '/BlogTemplate/BlogList.html', controller: 'ListBlog' })
.when('/Details/:ID', { templateUrl: '/BlogTemplate/BLogDetails.html', controller: 'DetailsBLog' })
.when('/blogcategory/:ID', { templateUrl: '/BlogTemplate/blogcategoryList.html', controller: 'BlogCategory' })
.otherwise({ templateUrl: '/BlogTemplate/BlogList.html', controller: 'ListBlog' });
}])
everything is work fine rough is working fine but the problem is in blogcategoryList.html page, i have a javascript function where user show list type view or grid type view but the problem is when the function is fire
automatically the ng-route is fire and
otherwise({ templateUrl: '/BlogTemplate/BlogList.html', controller: 'ListBlog' })
is fired and BlogTemplate/BlogList.html page is render
i want to stay in /BlogTemplate/blogcategoryList.html page
this is my javascript function
<script>
function showhide(id) {
debugger;
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName("tt");
for (var i = 0; i < divs.length; i = i + 1) {
$(divs[i]).fadeOut("slow");
}
$(divid).fadeIn("slow");
if (id = "listshow") {
$("#list > a").addClass("list-grid Active");
$("#grid > a").removeClass("Active");
}
else {
$("#grid > a").addClass("list-grid Active");
$("#list > a").removeClass("Active");
}
}
return false;
}
$(document).ready(function () {
// document.getElementById("listshow").fadeIn("slow");
$("#listshow").fadeIn("slow");
});

Redirect to UI-Route after Login Successfully

How to redirect to Home Page after Login successful,
I am using UI-router and below is my ui-router code.
var myrouting=angular.module('routingDemoApp', ['ui.router'])
myrouting.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("", "/index")
$stateProvider
.state('index', {
url: "/index",
templateUrl: "../Views/home.html"
})
.state('contactus', {
url: "/contactus",
templateUrl: "../Views/contactus.html",
})
.state('home', {
url: "/home",
templateUrl: "../Views/home.html",
})
.state('myModal', {
url: "/myModal",
templateUrl: "../Views/SignInPage.html",
})
}]);
I have a button element calling ng-click='login function' for validation Username and Password. once credentials are valid i want to redirect a page to "Home.html"
How to call ui-route after successfully login in below function?
var mymodule2 = angular.module('module2', []);
mymodule2.controller('controller2', function ($scope) {
$scope.loginFunction = function () {
alert("Login");
if ($scope.username == 'abcd' && $scope.password == 'hello123') {
console.log('Login sucessfull');
***// Redirect to Home Page.***
}
}
});
You can just use $state.go("home"); like this, where the "home" is the state name where you would like to go:
var mymodule2 = angular.module('module2', []);
mymodule2.controller('controller2', function ($scope, $state) {
$scope.loginFunction = function () {
alert("Login");
if ($scope.username == 'abcd' && $scope.password == 'hello123') {
console.log('Login sucessfull');
$state.go("home");
}
}
});
Use `$state.go("home");
var mymodule2 = angular.module('module2', []);
mymodule2.controller('controller2', function ($scope) {
$scope.loginFunction = function () {
alert("Login");
if ($scope.username == 'abcd' && $scope.password == 'hello123') {
console.log('Login sucessfull');
// add $state.go here
$state.go("home);
}
}
});

Why can't i use the $http service in a route resolve?

I want to make my views show only after the initial data is fetched and i am trying to accomplish this with a route resolve, but i can't get it to work. What am i doing wrong? Also my angular skills are a bit shabby so i aplogize in advance if my question is dumb.
Application.js :
var Application = angular.module('ReporterApplication', ['ngRoute']);
Application.config(['$routeProvider', '$interpolateProvider',
function($routeProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
$routeProvider
.when('/packing/scan.html', {
templateUrl: 'packing/scan.html',
controller: 'PackingScanController',
resolve: {
initData : Application.PackingScanInit()
}
})
.when('/packing/stats.html', {
templateUrl: 'packing/stats.html',
controller: 'PackingStatisticsController'
})
etc
and here is my Scan.js file :
Application.PackingScanInit = function ($q,$timeout,$http) {
var serverData = "";
$http.get('/packing/scan.action')
.success(function(data){
serverData = data;
})
.error(function(data){
serverData = data;
});
return serverData;
}
Application.controller('PackingScanController', ['initData', '$scope', '$http', function(initData, $scope, $http) {
var packer = this;
// Message log model
packer.messageLog = [{
status : "",
message : null
}];
the files are included in this order.
service are singletons means there are initialized only one but time but if you simply return from service it will be called one time but if you return a function from service it will be called again and again .See Below Sample for working.
var app = angular.module('ajay.singhApp', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
resolve: {
myVar: function (repoService) {
return repoService.getItems().then(function (response) {
return response.data;
});
}
}
})
.when('/view2', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/view1'
});
}]);
app.factory('repoService', function ($http) {
return {
getItems: function () {
return $http.get('TextFile.txt');
}
};
});
Try this:
Application.PackingScanInit = function ($q,$timeout,$http) {
return $http.get('/packing/scan.action')
.success(function(data){
return data;
})
.error(function(data){
return data;
});
}
Also you have to adjust your resolve to this:
resolve: {
initData : Application.PackingScanInit
}
Here is a specific working example:
(function() {
angular.module('app',['ngRoute']);
function TestCtrl($scope, initData) {
$scope.value = initData;
}
angular.module('app').config(function($routeProvider) {
$routeProvider.otherwise({
template: '`<p>Dude {{value}}</p>`',
controller: TestCtrl,
resolve: {
initData: function($http) {
return $http.get('test.json') //change to test-e.json to test error case
.then(function(resp) {
return resp.data.value; //success response
}, function() {
return 'Not Found'; // error response
});
}
}
});
});
})();
http://plnkr.co/edit/SPR3jLshcpafrALr4qZN?p=preview

Ionic Angular Firebase pass value to another tab

I'm new on Ionic, and I have been a couple of days with this problem.
I create an app from chat examples, and I want to connect and read to my firebase database. The first part is woking.- I can retreive and show data from firebase, but my problem is when I click on the "Item list" and want to show detail description, I don not understand how to pass value and get the data again.
Here are my scripst:
app.js ( I'm only showing part of them )
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','firebase'])
.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)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: "/tab",
abstract: true,
templateUrl: "templates/tabs.html"
})
// Each tab has its own nav history stack:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
}
})
.state('tab.chats', {
url: '/chats',
views: {
'tab-chats': {
templateUrl: 'templates/tab-chats.html',
controller: 'ChatsCtrl'
}
}
})
.state('tab.chat-detail', {
url: '/chats/:chatId',
views: {
'tab-chats': {
templateUrl: 'templates/chat-detail.html',
controller: 'ChatDetailCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/dash');
});
Here is my services file --- services.js where I connect to Firebase
angular.module('starter.services', [])
.factory('fireBaseData', function($firebase) {
// Might use a resource here that returns a JSON array
var ref = new Firebase("https://scorching-fire-921.firebaseio.com/")
refCorales = new Firebase("https://scorching-fire- 921.firebaseio.com/corales/");
var fireBaseData = {
all: refCorales,
get: function (chatId) {
return $firebase(ref.child('refCorales').child(chatId)).$asObject();
}
};
return {
ref: function() {
return ref;
},
refCorales: function() {
return refCorales;
}
}
});
And finally here is my controller.js
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope) {})
.controller('ChatsCtrl', function($scope, $firebase, fireBaseData) {
$scope.corales = $firebase(refCorales);
})
.controller('ChatDetailCtrl', function($scope, $stateParams, fireBaseData) {
$scope.corales = refCorales.get($stateParams.chat$id);
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
When I click on any item of the list, I'm receiving the following error message: TypeError: refCorales.get is not a function
Any idea how to avoid this erro?
In advance, thank you !
Victor
The problem i see is your services code is very unclear and not returning a way to acces var fireBaseData. Also why are you making two firebase references and not simple using ref.child('corales')?
This would be my solution:
.factory('fireBaseData', function($firebase) {
//Firebase reference
var ref = new Firebase("https://scorching-fire-921.firebaseio.com/")
return {
ref: function(){
return ref;
},
//I don't know if this is actually necessary
refCorales: function(){
return ref.child('corales');
},
get: function(chatId){
$firebase(ref.child('corales').child(chatId)).$asObject();
}
};
})
Update
Also some changes for your controller:
.controller('ChatsCtrl', function($scope, fireBaseData) {
$scope.corales = fireBaseData.refCorales();
})
.controller('ChatDetailCtrl', function($scope, $stateParams, fireBaseData) {
$scope.corales = fireBaseData.get($stateParams.chat$id);
})

Resources