Stop routing on click event in template in angularjs - 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");
});

Related

run function and location path issue

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("/")
}
})
});

Separate nav from ng-view

I'm brand new to Angularjs and am trying to set up a new site but I'm confused as to the set up. I have a module and am using $route to successfully navigate but I'm lost as to what to do with my nav. When I load the module I want to read my database for a list of links that the user is allowed to access then spit them out in the nav. I don't want to repeat this in every view because I don't need to. So I'm trying to figure out how to run the ajax call once and then keep changing the view (I'd also like to add a class .selected to whatever view they're on). How would I go about doing that, with a directive?
(function () {
var app = angular.module('manage', ['ngRoute', 'manageControllers']);
/*
I've tried this but obviously $http isn't injected. Can I even do that?
var thisApp = this;
$http.get('/test/angular/php/angular.php', {params: {'function': 'nav'}}).then(function successCallback(response) {
});
*/
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
}).
when('/inventory/', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
when('/inventory/:mvKey', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
when('/inventory/:mvKey/:tab', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
/* etc...*/
}
]);
})();
EDIT:
My attempt at getting the nav to run once
controllers.js
var manageControllers = angular.module('manageControllers', []);
var thisApp = this;
nav = null;
navSelected = '/';
manageControllers.controller('NavCtrl', ['$scope', '$http', function($scope, $http) {
if (thisApp.nav === null) {
$http.get('php/angular.php', {params: {'function': 'nav'}}).then(function successCallback(response) {
console.log(response.data);
thisApp.nav = response.data;
$scope.nav = thisApp.nav;
$scope.select = thisApp.navSelected;
});
} else {
$scope.nav = thisApp.nav;
$scope.select = thisApp.navSelected;
}
}]);
manageControllers.controller('DashCtrl', ['$scope', function($scope) {
thisApp.navSelected = '/';
}]);
I would swith to UI Router (https://github.com/angular-ui/ui-router) instead of $route. It allows you being much more flexible with your routing.
A Small example:
app.config(['$stateProvider',
function($stateProvider) {
$stateProvider.
state('/', {
url: '/',
views: {
'': {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
},
'nav#': {
templateUrl: 'path/to/nav.html',
controller: 'NavCtrl'
},
}
}).
state('/inventory/', {
url: '/',
views: {
'': {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
},
'nav#': {
templateUrl: 'path/to/nav.html',
controller: 'NavCtrl'
},
}
}).
// ...
and in your index.html
<div ui-view="nav"></div>
<div ui-view ></div>
Take a closer look at UI Router's doc, there's much more you can do with it!

Is the page loading twice

When the page loads, the alert fires twice. I am expecting it to fire only once.
This is causing duplicate data insertion in an array inside init function.
Why is this happening. Is it something to do with the routing definitions. How to stop it.
indexctrl.js:
app.controller("indexctrl", function ($scope, $routeParams) {
var uPId = $routeParams.pqid;
var uCId = $routeParams.cid;
if (uPId != null && uCId != null) {
//some other code
}
else {
alert('test');
init();
}
var init = function(){
//some code
}
}
app.js:
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'App/views/index.html',
controller: 'indexctrl'
})
.when('/Index', {
templateUrl: 'App/views/index.html',
controller: 'indexctrl'
})
.when('/Index/pqid/:pqid/cid/:cid', {
templateUrl: 'App/views/index.html',
controller: 'indexctrl'
})
.otherwise({
redirectTo: '/'
});
}]);
1. Check your controller is declared in html file as well.
2.The link which is referring to routes should be like this <a href="#/Index">
3.If your working with another frame works like ionic. it has aleardy angular.js file.so check how many time your loading script file.

AngularJS - Save data to $scope using routes?

i am just learning basics of angular and today it started to change my app using a factory to get data and implementing route provider ! So far everything works fine! But when I try to add data on another view and head back to my list view scope is reloaded again from factory and no added data shows up.
My approach won't work because each time change my view I will call my controller which reloads data from factory! What can I do to make my Add template will work and changes data everywhere else too.
Maybe somebody can give me a tip how to cope with this problem ?
script.js
var app = angular.module('printTrips', ['ngRoute']);
app.factory('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});
app.controller('TripController', function($scope, $filter, tripFactory) {
$scope.trips = [];
tripFactory.getTrips().success(function(data){
$scope.trips=data;
var orderBy = $filter('orderBy');
$scope.order = function(predicate, reverse) {
$scope.trips = orderBy($scope.trips, predicate, reverse)};
$scope.addTrip = function(){
$scope.trips.push({'Startdate':$scope.newdate, DAYS: [{"DATE":$scope.newdate,"IATA":$scope.newiata,"DUTY":$scope.newduty}]})
$scope.order('Startdate',false)
$scope.newdate = ''
$scope.newiata = ''
$scope.newduty = ''
}
$scope.deleteTrip = function(index){
$scope.trips.splice(index, 1);
}
});
});
view.js
app.config(function ($routeProvider){
$routeProvider
.when('/',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view1',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view2',
{
controller: 'TripController',
templateUrl: 'view2.html'
})
.when('/addtrip',
{
controller: 'TripController',
templateUrl: 'add_trip.html'
})
.otherwise({ redirectTo: 'View1.html'});
});
Here is my plunker
Thanks for your help
You should use Service instead of Factory.
Services are loaded each time they are called. Factory are just loaded once.
app.service('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});

AngularJS - How to disable access from URL

I'm working with routes :
App.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'orders/list',
controller: OrderController
});
$routeProvider.when('/editOrder', {
templateUrl: 'addOrder/editOrder',
controller: ActionController
});
$routeProvider.otherwise({redirectTo: '/home'});
I want to navigate to the edit page only when a button is clicked, but this definition allows access via url from browser also. Is it possible to disable access via url ?
You can use $routeChangeStart event to implement custom logic on route to be changed and veto navigation depending on some condition/permission. In the following example you can navigate to /edit route only if you have granted permissions, which you can grant or revoke using PermissionsService service. In the following example you can try to navigate via direct link and see that you are redirected to default route, and when you click Edit button you are redirected to the relevant route. Also, if you are on /edit route and make browser back and forward, you can notice that you can't go back to /edit route.
HTML
Home
Edit
<div ng-view></div>
<button ng-click="edit()">Edit</button>
JavaScript
angular.module('app', ['ngRoute']).
config(['$routeProvider', function($routeProvider){
$routeProvider.when('/home', {
templateUrl: 'list.html',
controller: 'OrderController'
});
$routeProvider.when('/edit', {
templateUrl: 'edit.html',
controller: 'ActionController'
});
$routeProvider.otherwise({redirectTo: '/home'});
}]).
run(['$rootScope', '$location', 'PermissionsService', function($rootScope, $location, PermissionsService) {
$rootScope.edit = function() {
PermissionsService.setPermission('edit', true);
$location.path('/edit');
};
$rootScope.$on("$routeChangeStart", function(event, next, current) {
if (next.templateUrl === "edit.html") {
if(!PermissionsService.getPermission('edit')) {
$location.path('/');
}
PermissionsService.setPermission('edit', false);
}
});
}]).
service('PermissionsService', [function() {
var permissions = {
edit: false
};
this.setPermission = function(permission, value) {
permissions[permission] = value;
}
this.getPermission = function(permission) {
return permissions[permission] || false;
}
}]).
controller('OrderController', [function() {}]).
controller('ActionController', [function() {}]);
Live example here.
You can use the resolve property and set some variable on an external service:
App.factory('editMode', function(){
var editMode = false;
return {
getEditMode: function(){ return editMode; },
setEditMode: function(edit) { editMode = edit; }
}
}
And then on the route:
$routeProvider.when('/editOrder', {
templateUrl: 'addOrder/editOrder',
controller: ActionController,
resolve: function(editMode){
if(!editMode.getEditMode()) {
$location.path( "/" );
}
}
});

Resources