ng-route handling outside the scope - javascript

Edit - Added a plunkr http://plnkr.co/edit/euD4FG?p=preview
the RouteController is not getting called, please have a look
Fiddle: http://jsfiddle.net/smartdev101/tv1p9n4h/
angular.module(this.constructor.NAME, ['ngRoute'])
.config(function($routeProvider){
self.config($routeProvider)
})
.controller("RouteController", function($scope, $routeParams){
self.routeController($scope, $routeParams)})
angular.bootstrap(document.getElementById("browser"), [this.constructor.NAME]);
});
HTML
<div id="browser"></div>
<ul>
<li>
Racu, Cristian
</li>
<li>
Shnider, Brent
</li>
<li>
Suess, Mike
</li>
</ul>

Well, spell error & missing ng-view. Should be controller in $routeProverder.when, just change your config into this:
config: function($routeProvider) {
$routeProvider
.when('/attendees/:param', {
template:"no template",
//constroller: "RouteController"
controller: "RouteController"
})
},
And add ng-view into your html. Seems ngRoute won't work without ng-view
<div id="browser">
<div ng-view></div>
</div>
Here is JSFIDDLE.

Related

href angularjs not routing

I have defined my href links like this:
<div id="left-menu">
<div class="sub-left-menu scroll">
<ul class="nav nav-list">
<li><div class="left-bg"></div></li>
<li class="time">
<h1 class="animated fadeInLeft">21:00</h1>
<p class="animated fadeInRight">Sat,October 1st 2029</p>
</li>
<li class="active ripple">
<a href="#hosts">
<span class="fa-home fa"></span> Dashboard
</a>
</li>
<li class="ripple">
<a href="hosts/hosts.html">
<span class="fa fa-calendar-o"></span> Calendar
</a>
</li>
</ul>
</div>
</div>
However when I click on the <a> tags it does not seem to pull back the content held within the my hosts.html file. The url in the browser also does not change with the base url being http://localhost/dashboard/#/main and when I click host the desired output should be http://localhost/dashboard/#/hosts with the correct content displaying. Here is the theme pack I am using http://akivaron.github.io/miminium/
Here are my angularjs files starting with the app itself 'dashApp'
'use strict'
// Declare app level module which depends on views, and components
angular.module('dashApp', [
'ngRoute',
'dashApp.main',
'dashApp.hosts'
])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.otherwise({redirectTo: '/main'});
}]);
here is my main:
'use strict'
angular.module('dashApp.main', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/main', {
templateUrl: 'main/main.html',
controller: 'mainController'
})
}])
.controller('mainController', function($scope, $http, $window){
});
and here is my hosts file:
'use strict'
angular.module('dashApp.hosts', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/hosts', {
templateUrl: 'hosts/hosts.html',
controller: 'hostsController'
})
}])
.controller('hostsController', function($scope, $http, $window){
});
and here is the project structure:
https://gyazo.com/fb5e2a2651fe8cc460fde783237ddd9c
Remove the trailing / in the href's. They need to match the url in your routing config
Example
<a class="tree-toggle nav-header" href="#/main/" target="_self">
Should be
<a class="tree-toggle nav-header" href="#/main" >
"Href" links should be inside ng-app and ng-view also inside the app. Like Below
<div ng-app="myApp" ng-controller="myController">
home
books
<div ng-view></div>
</div>
first of all check the above then update your js file like below:-
var app=angular.module("myApp",['ngRoute']);
app.config('$routeProvider',function($routeProvider){
$routeProvider
.when('/home',{
templateUrl:'path/some.html'
})
});
feel free to ask if any doubt.
I think you should remove the hash.
<a class="tree-toggle nav-header" href="/main">link</a>

How do i define routing to navigate to details page when link clicked

I need some help to implement list and details page.
I have motorList.html page where i am listing all motors as hyperlink retrieved from server (database).
motorList.html
<div>
<ul class="phones">
<li ng-repeat="motor in motors" >
<a href="#/motors/{{motor.Id}}">{{motor.Name}}
</li>
</ul>
</div>
I want when user clicks on any motor link, system should navigate to motorDetails.html page and show the details for clicked/selected motor.
For this i defined my routes as following in app.js
app.js
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/motors', {
templateUrl: 'View/motorlist.html',
controller: 'motorController'
}).
when('/motors/:motorId', {
templateUrl: 'View/motordetail.html',
controller: 'motorDetailsController'
}).
otherwise({
redirectTo: '/motors'
});
}]);
motorDetails.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<ul class="phones">
<li ng-repeat="motor in motors" class="thumbnail">
<p>{{motor.Name}} {{motor.Make}} {{motor.Model}} {{motor.Year}} {{motor.Kilometers}} {{motor.Price}} {{motor.Color}} {{motor.SellerType}}</p>
</li>
</ul>
</div>
</body>
</html>
motorDetailsController.js
var app = angular.module('myApp', ['ngSanitize', 'ui.select']);
app.controller('motorDetailsController', function ($scope, $routeParams, motorService) {
$scope.motors = null;
$scope.getMotorDetails = function (Id) {
motorService.getByMake(Id)
.success(function (motors) {
$scope.motors = motors;
})
.error(function (error) {
$scope.status = 'Unable to load motor data: ' + error.message;
});
}
});
Problem:
When i click on any motor hyperlink, it does not navigate to motorDetails.html page but url changes e.g. http://localhost:12270/View/motorList.html#/motors/161.
I am new to AngularJs routing and for sure i am missing something here but not sure what is wrong.
Could anyone guide me please.
Thanks
You should add ng-view directive on your page, which will show the template loaded from the $routeProvider by watching the URL. You need to add ng-view directive somewhere in your body.
Additionally you should incorporate the changes suggested by #Dvir.
Markup
<body>
<div>
<ul class="phones">
<li ng-repeat="motor in motors" class="thumbnail">
<p>{{motor.Name}} {{motor.Make}} {{motor.Model}} {{motor.Year}} {{motor.Kilometers}} {{motor.Price}} {{motor.Color}} {{motor.SellerType}}</p>
</li>
</ul>
</div>
<div ng-view></div>
</body>
Update
Ideally you should have ng-view directive there in motorList.html, which gets loaded(But I'm treating it as the index.html page where all the css & js references are there)
Also you don't need to include the html, head & body tag in partial as its going to treated as partial, So remove body,head & html tag and make it simple by placing required template only.
motorDetails.html
<div>
<ul class="phones">
<li ng-repeat="motor in motors" class="thumbnail">
<p>{{motor.Name}} {{motor.Make}} {{motor.Model}} {{motor.Year}} {{motor.Kilometers}} {{motor.Price}} {{motor.Color}} {{motor.SellerType}}</p>
</li>
</ul>
</div>
That's because href is a regular attribute and it's not evaluated by angularJs.
To make this expression to be your desired link you have to use ng-href so angularJs will evaulate the expression and assign it to an href html attirbute.
You have to change
href="#/motors/{{motor.Id}}"
to
ng-href="#/motors/{{motor.Id}}"
In addition to get its id. you have to use $routeParams in the controller.
For instance:
var id = $routeParams.motorId
UPDATE
I missed that but #Pankaj Parkar right. You have to use ng-view to make the routeProvider to assign the relevant view to the right placeholder.
How to use ng-view ?
You have to make an element where do you want to make the view appear.
It can be part of the page or all the page.
Put the element wherever you want and you'll understand.
For instance:
<body>
<div id="nav">
</div>
<ng-view>
<!-- this is the place your html template will apear -->
</ng-view>
</body>

Angularjs and routeParams

I have a piece of code that is getting JSON data from a local server. I am trying to display those data into a page and then when i'll click on a product i want to see the details of it. So far i can display all my products into a page but when i'm heading to the details page i got an error Cannot read property 'id' of undefined. Can you please help me out?
This is my code so far.
app.js
'use strict';
angular.module('app', []).
config(function($routeProvider){
$routeProvider.
when("/", {templateUrl: "/partials/products.html"}).
when("/details/:id", {templateUrl: "/partials/details.html", controller: DetailsCtrl}).
otherwise({redirectTo: "/"});
})
function AppCtrl($scope, $http){
$http.get('http://localhost:3000/api/products/727617361726372')
.success(function(data){
$scope.productList = data;
/*$scope.filterProductsByCategory = function(category){
$scope.search = category
};*/
})
.error(function(data){
console.log("Error!: ");
});
}
function DetailsCtrl($scope, $routeParams){
$scope.item = $scope.productList[$routeParams.id];
}
details.html
<h2>This is the details pages</h2>
product id: {{ item.product_id }}
<br/>
product name: {{ item.product_name}}
index.html
<div class="container" ng-app="app" ng-controller="AppCtrl">
<h1 class="text-danger">Welcome to our Store</h1>
<hr/>
<ng-view></ng-view>
</div>
products.html
<div class="col-lg-4 col-sm-6 col-xs-12" ng-repeat="product in productList">
<div class="thumbnail">
<img src="img/img3.jpeg">
<div class="caption">
<h4>{{ product.product_name }}</h3>
<p>Category: {{ product.category_name }} ({{ product.category_id }})</p>
<p class="text-muted">{{ product.product_details}}</p>
<ul class="list-inline">
<li>
<p class="product-price btn">€ {{ product.product_price }}</p>
</li>
<li>
Add to Cart
</li>
</ul>
</div>
</div>
Thanks!!!
you are getting the productList in your AppCtrl. If you want to access a specific item in your DetailsCtrl you'll need to get the specific item since you can't access AppCtrl scope variables in another Ctrl.
The best way to do this would be to create an extra rest call for getting a single item.
A quick way to fix your code, although I really don't recommend it would be to use $rootcope in your AppCtrl
I'd suggest reading Angular Docs on $scope. It might give you a better understanding how scopes work in angular:
https://docs.angularjs.org/guide/scope#!
I assume you have injected ngRoute correctly.
angular.module('app', ['ngRoute'])
Other than that there is nothing wrong with your code.
Demo
Just check your code again.

Template not loading in Angular route

Issue is quite simple. I have been trying for hours now but just couldn't get the template to load via angularJS client side routing. Not using any server side routing.
So, used various combinations of paths. If I use "/home" in button href it straight away gives error that it couldn't find "/home". But with "#/home", I don't get that error but it still wouldn't load the template.
Any help would be greatly appreciated.
Created a new plunker: http://plnkr.co/edit/F7KoWbBuwsXOQLRPF0CN?p=preview
Template directory:
Project ---
|
|
CSS
|
|
JS
|
|
templates---
|
|
home.html
JS:
var myApp = angular.module("myApp",['ngRoute']);
myApp.controller('appController',function($scope,$http){
//mytext = 0; instantiating variables without using var gives referencing error due to "use strict";
$scope.angular = angular;
$scope.mytext = "Harsh";
$scope.formSuccess = false;
$http({method:"GET", url:"JS/carousel-data.json"}).
success(function(data) {
$scope.carouselData = angular.fromJson(data);
}).
error(function(data) {
console.log("Error loading images");
});
myApp.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'templates/home.html',
controller: 'appController'
})
.when('/edit', {
templateUrl: 'templates/home.html',
controller: 'appController'
});
});
HTML:
<body ng-controller="appController">
<header id="pageHeader" class="col-md-12 col-sm-12 col-xs-12 header">
<nav class="col-md-5 col-sm-6 col-xs-10 menu">
<ul class="nav nav-pills" id="menuLinks">
<li class="dropdown visible-xs">
Sapient <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Home</li>
<li>Edit</li>
</ul>
</li>
<li role="presentation" class="hidden-xs" >Home</li>
<li role="presentation" class="hidden-xs" >Edit</li>
</ul>
</nav>
</header>
<div ng-view></div>
</body>
It's rather unclear how you've set up things? Is the HTML your index or is that your home.html?
Secondly you already declare the controllers of your pages to be appController, no need to define that with the ng-controller directive anymore.
Apart from that you're loading the same template on each href, could it be that you're just seeing the same page like declared?
$routeProvider
.when('/home', {
templateUrl: 'templates/home.html', <---
controller: 'appController' <---
})
.when('/edit', {
templateUrl: 'templates/home.html', <---
controller: '**appController'<--
});
It should be noteworthy that there is a more extensive module for routing. You can find it at ui-router.

ngClass not updating the class

I am using angularJS with bootstrap to design a navigation on my application. I have defined a main controller and inside the main controller I call different page views using the ng-view attribute and then these individual views have their own controllers.
I am using the ng-class attribute to add the active class to my links, however, it is not working. The expression evaluates to true or false but the ng-class does not updates the class="active" on the elements.
On my home page I have the following code -
<section ng-controller="dashBoardCtrl" class="container">
<section class="row">
<h1>DME DashBoard | <small>WFM HeadCount</small> </h1>
</section>
<section class="row">
<ul class="nav nav-tabs">
<li role="presentation" ng-class="{active: {{path=='/'}}}"><a ng-href="#/">Home</a></li>
<li role="presentation" ng-class="{active: {{path=='/login'}}}"><a ng-href="#/login">Login</a></li>
</ul>
</section>
<section ng-view></section>
</section>
This is how the routes are configured on the app -
dmeDash.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/views/home.html',
controller: 'homePageCtrl'
})
.when('/login', {
templateUrl: '/views/login.html',
controller: 'loginCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
The dashBoardCtrl have the following code -
dmeDashControllers.controller('dashBoardCtrl', ['$scope','$location', function($scope, $location) {
$scope.path = $location.$$path;
$scope.$watch('path',function(n,o) {
})
}]);
Home Page Controller has the following code -
dmeDashControllers.controller('homePageCtrl', ['$scope','$location', function($scope, $location) {
$scope.$parent.path = $location.$$path;
}]);
The log in page controller has the following code -
dmeDashControllers.controller('loginCtrl', ['$scope','$location', function($scope, $location) {
$scope.$parent.path = $location.$$path;
}]);
When I click from Home page to Login page the active class is not removed from home page link and not applied to the login page as well, however, when I view the code in firebug the expressions evaluates to true or false when the page changes.
When I refresh on individual pages the ng-class works correctly but not when using the hyperlinks, please suggest.
The syntax is wrong on the template. It should be:
<li role="presentation" ng-class="{'active': path==='/'}"><a ng-href="#/">Home</a></li>
And as style guide try using the === instead of the simple == because of type coercion. Or test agains truthy or falsy

Categories

Resources