angularjs ngroute not working - angularjs

i am new in angularjs i have a index page with some data with anchor tag when user click in a particular anchor tag page redirect to list page and show data but ngRoute not working and also the not getting the query string value. Where i wrong
this is my index page
<div class="all_cat" ng-repeat="state in statelist">
<h2>{{state.Statename}}</h2>
<div class="cat-col-4" ng-repeat="citylist in state.city">
<ul>
<li><i class="fa fa-caret-right"></i>{{citylist.cityname}} ({{citylist.jobcount}})</li>
</ul>
</div>
<div class="clear"></div>
</div>
and this is my js
var app = angular.module('angularTable', ['ngSanitize', 'ui.select', 'angularTrix', 'ngRoute']);
app.config(function($routeProvider) {
debugger;
$routeProvider
.when('/JobList:ID', {
templateUrl: 'job/JobList.cshtml',
controller: 'joblist'
})
});
app.controller('joblist', function($scope, $routeParams) {
debugger;
$scope.message = 'Clicked person name from home page should be display here';
$scope.person = $routeParams.ID;
});
i am not under stand where i do wrong

Ass braja lal Mahanty tell you might want /JobList/:ID instead of /JobList:ID.
So you have to set state as:
$routeProvider
.when('/JobList/:ID', {
templateUrl: 'job/JobList.cshtml',
controller: 'joblist'
})
});

Related

I want to show student details by passing student id via routing in angularjs. But I am unable to do it

I am new to Angular JS and try to view student details by passing student id using routing
I have coded a bit but not geeting where to add the details of students and how to pass student id
this is the code for index.html
<div>
<div>
<div>
<ul>
<li> Add Student </li>
<li> Show Student </li>
</ul>
</div>
<div >
<div ng-view></div>
</div>
</div>
</div>
this is the code for app.js
```````````````````````````````````````````
var myApp = angular.module('stuApp', []);
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/add', {
templateUrl: 'add_student.html',
controller: 'addCtrl'
}).
when('/show', {
templateUrl: 'show_student.html',
controller: 'showCtrl'
}).
otherwise({
redirectTo: '/add'
});
}]);
myApp.controller('addCtrl', function ($scope) {
$scope.message = 'This is Add new Student screen';
});
myApp.controller('showCtrl', function ($scope) {
$scope.message = 'This is Show Student screen';
})
I want to add student details in via form but dont dont know how to add those values in controller
add_student.html
````````````````````````````
<script type="text/ng-template" id="add_student.html">
<h2>Add New Student</h2>
{{ message }}
</script>
show_student.html
<script type="text/ng-template" id="show_student.html">
<h2>Show Order</h2>
{{ message }}
</script>
I want the output as to pass object in controller display the students name and by clicking on the name student details should be displayed.
Hi Akansha for pass the parameters through routing in the url you need to change your $routeProvider in something like that:
when('/add/:StudentId', {
templateUrl: 'add_student.html',
controller: 'addCtrl'
})
This means that if your url is /add/1837 the parameter StudentId would have the value 1837.
For get the value of StudenId in your controller you can use $routeParams.
So for example your controller could be like the following one:
myApp.controller('showCtrl', function ($scope, $routeParams) {
$scope.message = 'This is Show Student screen';
var studentId = $routeParams.StudentId;
})
You can obtain more information from the following link URL-Routing - GitHub
Also there are other ways of access the url parameters, they are described in the following SO questions Access URL parameters in Angularjs in the Controller and How to get the url parameters using AngularJS
In Your app.js route config code, add route param ID like below
when('/show/:id', {
templateUrl: 'show_student.html',
controller: 'showCtrl'
})
In your index.html, pass ID through a tag
<ul>
<li> Add Student </li>
<li> Show Student </li>
</ul>
And in show controller, inject $routeParams first,
myApp.controller('showCtrl', function ($scope,$routeParams) {
$scope.studentID = $routeParams.id; //passsed ID
$scope.message = 'This is Show Student screen';
})
//you can use student ID to filter your data in showStudent.html

it just keep loading the same page with angular ngRoute?

I am learning angular by building a simple bookstore web app using nodejs as a restful api server. I built the server and it works fine, but once it comes to the front end I face an issue. I built the main page using angular ngRoute to get the data from the server and presented as following:
the picture and the title and the description angular read it with no problem but once I press the button "View Details" I should be redirected to a details page using the book id from the server.
From the front End the route provider:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider.when('/',{
controller: 'BooksController',
templateUrl: 'views/books.html'
})
.when('/books',{
controller: 'BooksController',
templateUrl: 'views/books.hrml'
})
.when('/books/details/:id',{
controller: 'BooksController',
templateUrl: 'views/book_details.html'
})
.when('/books/add', {
controller: 'BooksController',
templateUrl: 'views/add_book.html'
})
.when('/books/edit/:id', {
controller: 'BooksController',
templateUrl: 'views/edit_book.html'
})
.otherwise({
redirectTo: '/'
})
});
Books Controller:
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location',
'$routeParams', function($scope, $http, $location, $routeParams){
console.log('BooksController loaded...');
$scope.getBooks = function(){
$http.get('/api/books').then(function(response){
$scope.books = response.data;
});
}
$scope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
}
}]);
books html where the panel being designed:
<div class="panel panel-default" ng-init="getBooks()">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class="row">
<div ng-repeat="book in books">
<div class="col-md-6">
<div class="col-md-6">
<h4>{{book.title}}</h4>
<p>{{book.description}}</p>
<a class="btn btn-primary"
href="#/books/details/{{book._id}}">View Details</a>
</div>
<div class="col-md-6">
<img class="thumbnail" src="{{book.image_url}}">
</div>
</div>
</div>
</div>
</div>
</div>
This the details book html where by clicking the button it must be redirected to:
details_book.html
<div class="panel panel-default" ng-init="getBook()">
<div class="panel-heading">
<h3 class="panel-title">{{book.title}}</h3>
</div>
<div class="panel-body">
<div class "row">
<div class ="col-md-4">
<img src="{{book.image_url}}">
</div>
<div class ="col-md-8">
<p>{{book.description}}</p>
<ul class="list-group">
<li class="list-group-item">Genre: {{book.genre}}</li>
<li class="list-group-item">Author: {{book.author}}</li>
<li class="list-group-item">Publisher: {{book.publisher}}
</li>
</ul>
</div>
</div>
</div>
</div>
and this is the get request from the server to prove the server working find using a certain id
The error I get once I open the main page:
And this error I get once I press the button:
Note: Once I press the button it give me this url:
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
where the id is 599701c1f3da51117535b9ab which we can see it in the end of the url. But it should give url exactly such as:
http://localhost:3000/#!/books/details/599701c1f3da51117535b9ab
and once I write this url manually I get to the page which is the details with no problem but once I press the button from the book.html page I get the previews strange url again which is:
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
Which load no where.
This is the github url for all the documents:
https://github.com/AbdallahRizk/BookStore.git
Any suggestions Please!!
use $rootScope instead of $scope for getBook function
$rootScope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
init(getBook);
}
Note: add $rootScope to your BookController
Seems like I have hashprefix !, then my URL should also have ! after hash(#)
href="#!/books/details/{{book._id}}"
Since Angular 1.6 hashprefix is defaulted to !, you can disable this behavior by setting hashPrefix to ''(blank).
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
Note: This answer from, #Pankaj Parkar at I get a weird templateURL not as it suppose to give with angular?

template not displaying binded data after routed, on first click - AngularJS

Trying to route to different view template from the index page. Initially, the list on main index page gets loaded and the main.html gets loaded in ng-view, displaying it's text contents. The data from 'MainCtrl' is broadcasted properly and works fine. Now, the confusion is, when the item from the list is clicked, it gets routed to content template(content.html), but the content does not display the binded value on the first click on the list. But, after second click, it starts showing the binded values that is broadcasted from MainCtrl.
<body ng-app="myApp">
<div ng-controller="MainCtrl">
<ul ng-repeat="value in msg" ng-click="setSelectedValue(value)">
<li>
<a href='#/content'>{{ value }}</a>
</li>
</ul>
</div>
<div ng-view=""></div>
main.html:
<p>Select from the list.</p>
content.html:
//loads the selected item from the list on index page
<h3>Selected: {{ message }}</h3>
angular
.module('myApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/content', {
controller: 'ContentCtrl',
templateUrl: 'views/content.html'
})
.otherwise({
redirectTo: '/'
});
})
.factory('myService', function($http, $rootScope){
var sharedService ={};
sharedService.message = '';
sharedService.prepforBroadcast = function(value){
this.message = value;
this.broadcastItem();
};
sharedService.broadcastItem = function(){
$rootScope.$broadcast ('handleBroadcast');
};
return {
sharedService: sharedService
};
})
.controller('MainCtrl', function ($scope, myService) {
$scope.msg = data; //this will be json data
$scope.selectedValue;
$scope.setSelectedValue = function(value){
$scope.selectedValue = value;
myService.sharedService.prepforBroadcast(value);
}
})
.controller('ContentCtrl', function ($scope, myService) {
$scope.$on('handleBroadcast', function(){
$scope.message = myService.sharedService.message;
})
});
Not sure what exactly is the reason for not binding the data on the very first click even though when the template loads instantly. Any help or thought would be greatly appreciated. Scratching my head for a while.
<ul ng-repeat="value in msg" ng-click="setSelectedValue(value)">
check with out ng-click="setSelectedValue(value)" part. seems like ur click is going to handle by setSelectedValue(value) function
The ng-repeat and ng-click should be on li.
<ul>
<li ng-repeat="value in msg" ng-click="setSelectedValue(value)">
<a href='#/content'>{{ value }}</a>
</li>
</ul>

routeProvider in angularJS not acting right

Within my view I am outputting links. When I go to click a link it triggers the otherwise method in my routeProvider and ends up redirecting back to home. I need it to redirect indiv id and I need to be able to grab project.id from my view within my controller. May I please have some assistance. I'm kind of stuck.
My view:
<div class="container clearfix">
<div class="pagename sixteen columns fadeInUp animated">
<h1 style="font-family: Merriweather">Portfolio</h1>
</div>
</div>
<div class="container clearfix" ng-controller="portfolioController">
<ul style="padding-left: 20pt" class="large-block-grid-4 align-center">
<li class="part" ng-repeat="project in projects">
<a href="#/indiv?id={{ project.id }}">
<img src="{{ project.screenshot_uri }}" alt="">
</a>
<br><br>
<h4>{{ project.project_name }}</h4>
<p>{{ project.description }}</p>
</li>
</ul>
</div><br><br>
My app data:
var app = angular.module("app", ['ngRoute']).config(function($httpProvider, $routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'index.php/projects/projects/home',
controller: 'homeController'
});
$routeProvider.when('/portfolio', {
templateUrl: 'index.php/projects/projects/portfolio',
controller: 'portfolioController'
});
$routeProvider.when('/indiv:id', {
templateUrl: 'index.php/projects/projects/indiv',
controller: 'indiv_controller'
});
$routeProvider.when('/contact', {
templateUrl: 'index.php/projects/projects/contact',
controller: 'contactController'
});
$routeProvider.otherwise({ redirectTo: '/home' });
});
app.factory('pull_projects', function($http) {
return {
get_projects: function(callback) {
$http.get('index.php/projects/pull_projects').success(callback);
}
};
});
app.controller('portfolioController', function($http, $location, $scope, pull_projects) {
pull_projects.get_projects(function(results) {
$scope.projects = results;
});
});
app.controller('contactController', function($http, $location, $scope) {
});
app.controller('indiv_controller', function($http, $location, $scope, $routeParams) {
alert($routeParams.id);
});
app.controller('homeController', function($http, $location, $scope) {
});
Seems the problem is that you are defining the angular routing url and the url in the markup slightly different.
Route:
In the route url you are defining /indiv:id. However, this would match a url where the id was part of the indiv part. So, http://host/indiv123.
So, I would suggest changing this to: /indiv/:id. This will then match urls like this: http://host/indiv/123.
Markup:
In the HTML you are declaring the url as #/indiv?id={{ project.id }}. This will produce the url: /indiv?id=123.
To match our new angular route we need the template to be #/indiv/{{ project.id }} so that we produce a url like /indiv/123.
Hope this helps.
You should use :
ng-href="#/indiv?id={{ project.id }}"
instead of
href="#/indiv?id={{ project.id }}"
This ensures that {{ project.id }} is correctly resolved before it is used as a link.
This occurs because Angular not always gets the chance to intercept the data binding requests before the browser attempts to resolve href and src (<img src="">) attributes. Accordingly, you should use ng-src for images.

how do I change background image of application based on url or routing?

I would like to change the background image of the application(Html Body) based on the url. And this I want to do in angularJS only :)
For eg:
1) if user visits the url like this,
www.domain.com/view1
Bellow image is shown
2) If user visits url
www.domain.com/view2
I want show other image
app.js
var app = angular.module('app', []);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}])
app.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
}]);;
Controler.js
app.controller('MyCtrl1',function($scope){
$scope.viewBackground="body"
console.log($scope.viewBackground);
})
app.controller('MyCtrl2',function($scope){
$scope.viewBackground="profile"
})
in the partial html, I am just doing like this
<div class="span12">
<p>
{{$scope.viewBackground}}zxz
</p>
</div>
But some reason I am not able to get the value of viewBackground property value.
I'm not sure I understand you correctly, but I hope so.
You have 2 options.
First - use different controllers for each page view1 and view2.
And use ng-class directive on the pages:
HTML:
<!-- "page" View 1 -->
<div ng-controller="View1Ctrl">
<div ng-class="viewBackground"> View 1 </div>
</div>
<!-- "page" View 2 -->
<div ng-controller="View2Ctrl">
<div ng-class="viewBackground"> View 2 </div>
</div>
JS:
var app = angular.module('app', []);
function View1Ctrl($scope) {
$scope.viewBackground = "background-small"
}
function View2Ctrl($scope) {
$scope.viewBackground = "background-big"
}
On your CSS:
.background-small{
height:200px;
width:200px;
background: url('...img1...');
}
.background-big{
height:400px;
width:400px;
background: url('...img2...');
}
Second option - use .run block, where you will add some logic to change the bg-image, but this is a poor option
If your controller you can check the $routeParams param and then set a scope variable to control the background image.
function announcements_detail_controller($scope, $rootScope, $routeParams, $http, $location)
{ //console.log($routeParams);
$scope.css_class_for_background_image = 'xxxx';//
}

Resources