routeProvider in angularJS not acting right - angularjs

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.

Related

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?

angularjs ngroute not working

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'
})
});

Item Details Page using angularjs $routeParams

I am building an online store with angularjs and I am having a hard time figuring out how to link to the details.html and have it display the specific items details. Currently when I click on the view more button url will show the name of the item. The only way i can get it to show is by making a link like this: #/details/:{{item.name}}. Everything I've read online says it should be #/details/:name but that returns :name in the url and not details/:Macbook Pro as an example. If I do it the correct way it redirects back to the home page. Here's my code so far.
app.js
var myApp = angular.module('app', ['ngRoute']);
myApp.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$routeProvider.
when('/home',{
templateUrl: 'partials/home.html',
controller: "storeCtrl"
}).
when('/about',{
templateUrl: 'partials/about.html',
controller: "storeCtrl"
}).
when('/computers',{
templateUrl: 'partials/computers.html',
controller: "storeCtrl"
}).
when('/smartphones',{
templateUrl: 'partials/smartphones.html',
controller: "storeCtrl"
}).
when('/tablets',{
templateUrl: 'partials/tablets.html',
controller: "storeCtrl"
}).
when('/details/:{{item.name}}',{
templateUrl: 'partials/details.html',
controller: "storeCtrl"
}).
otherwise({
redirectTo: '/home'
});
}]);
myApp.controller('storeCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.homeHeading = 'All Products';
$scope.aboutHeading = 'About Us';
$scope.computersHeading = 'Computers';
$scope.smartphonesHeading = 'Smartphones';
$scope.tabletsHeading = 'Tablets';
$http.get('js/products.json').then(function(result) {
$scope.products = result.data;
});
$scope.minusOne = function(index) {
$scope.products[index].dislikes += 1;
};
$scope.plusOne = function(index) {
$scope.products[index].likes += 1;
};
}]);
computers.html
<div>
<h1>{{computersHeading}}</h1>
<div class="product col-md-4" ng-repeat="item in products | filter:search | filter:'Laptop'">
<img ng-src="{{ item.cover }}" >
<h3>{{ item.name }}</h3>
<p class="price">{{ item.price }}</p>
<p class=""> <b>Storage</b>: {{ item.specs.storage }}</p>
<p> <b>Memory</b>: {{ item.specs.memory }}</p>
<!----- Save ratings for details page
<div class="rating">
<p class="likes" ng-click="plusOne($index)">
<i class="fa fa-thumbs-up"></i>
{{ item.likes }} </p>
<p class="dislikes" ng-click="minusOne($index)"><i class="fa fa-thumbs-down"></i> {{ item.dislikes }} </p>
</div> -->
View Product
</div>
</div>
Again the only way to get the item name to show in the url is to have the brackets in the url and i know that is incorrect. Any help would be greatly appreciated.
I figured out, I needed to make a controller for the details page and then get the json data. I then changed my href link to
View Product

why angularjs controller loading twice

Here is my route config, I am using routeProvider to bind controller to view and not declaring ng-controller in my view still my controller loading twice, I searched for lot of solutions and tried every thing but no use.
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "app/views/home.html"
}).when("/login", {
controller: "loginController",
templateUrl: "app/views/login.html"
}).when("/regcars", {
controller: "RegCarsController",
templateUrl: "app/views/client/RegCars.html"
}).otherwise({ redirectTo: "/home/" });
Here is template(view)
<div class="col-md-6 box box-success pull-left">
<div class="box-header with-border">
<h3 class="box-title">My cars</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
{{CarName}}
</div>
</div>
And here is my controller
app.controller('RegCarsController', function ($scope) {
$scope.CarName = "MyCar";
alert('MyCar');
});
In my above code showing alert twice. Below I have link to call the view, tried with and with out slash at end of href link
<a href="#/regcars/">
<i class="fa fa-car fa-2x"></i> <span>My Cars</span>
</a>
Some proof of concept that controller is called many times. Strange.
On the other hand - the same code on JSFiddle - shows that controller is executed / fired only once.
angular.module('app', ['ngRoute']).config(function($routeProvider) {
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "app/views/home.html"
}).when("/regcars", {
controller: "RegCarsController",
templateUrl: "app/views/client/RegCars.html"
}).otherwise({ redirectTo: "/home" });
})
.run(function($templateCache) {
$templateCache.put('app/views/home.html', '<div>home tempalte</div>');
$templateCache.put('app/views/client/RegCars.html', '<div>cars template, car name: {{ CarName }}</div>');
})
.controller('homeController', function() {})
.controller('RegCarsController', function($scope) {
$scope.CarName = "MyCar";
console.log('Called many times')
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-route.min.js"></script>
<div ng-app='app'>
<ul><li><a href='#/'>Home</a></li><li><a href='#/regcars'>Cars</a></li></ul>
<ng-view></ng-view>
</div>

Angular, redirect from one controller to onother

I'm developing an application using angularjs starting from https://github.com/firebase/angularfire-seed project. I'm trying to redirect from a controller to another without success. I need to do this from controller because i have some controls to do before redirect. I'm using location object for do it..
Here is my code for redirect:
$scope.infostore = function() {
$location.path( 'store' );
}
Here is my route configuration:
angular.module('myApp.routes', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
authRequired: true,
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
});
$routeProvider.when('/apps', {
authRequired: true,
templateUrl: 'partials/apps.html',
controller: 'appsController'
});
$routeProvider.when('/store', {
authRequired: true,
templateUrl: 'partials/store.html',
controller: 'storeController'
});
$routeProvider.otherwise({redirectTo: '/home'});
}]);
But every time i call the method 'infostore' in appsController angular redirect me to 'home'
Why? I just try to use apply() without success on main scope.
Here is my store controller:
'use strict';
app.controller('storeController', function($location, $firebase, $modal, $scope, database, $http, $rootScope, $routeParams) {
var ref = database.returnRef("users/"+$rootScope.auth.user.uid+"/apps");
$scope.apps = $firebase(ref);
});
Here is store html:
<div class="container">
<br />
<div class="row">
<div class="col-md-12 text-center">
<h3>
<span>{{ 'myappslong' | translate }}</span>
</h3>
</div>
</div>
<br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
store
</div>
<div class="col-md-1"></div>
</div>
</div>
Here is the URL from the first controller: http://localhost:8000/app/index.html#/apps
Solved, there was an error in my html code. Using location.path works correctly.

Resources