AngularJS Router: redirect to different view - javascript

I am making my first AngularJS App followed by this tutorial:
https://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app
The problem is in my App when I direct to view 1, it works fine. It can load the HTML file with the information of all the drivers. However, when I click one specific driver, it can't load the HTML page for the particular driver. How can I redirect to the HTML page of the particular driver?
The App structure is
view 1:
view1.html
js
driver
---------driver.html
view 2
view2.html
<p>This is the partial for view 1.</p>
<input type="text" ng-model="filterTxn.Driver.givenName" placeholder="Search..."/>
<table>
<thead>
<tr><th colspan="4">Drivers Championship Standings</th></tr>
</thead>
<tbody>
<tr ng-repeat="driver in driversList | filter: filterTxn ">
<td>{{$index + 1}}</td>
<td>
<a href="#/view1/driver/{{driver.Driver.driverId}}">
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</a>
</td>
<td>{{driver.Constructors[0].name}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>
<p>detail page for a specific driver</p>
<section id="main">
<- Back to drivers list
<nav id="secondary" class="main-nav">
<div class="driver-picture">
<div class="avatar">
<img ng-show="driver" src="img/drivers/{{driver.Driver.driverId}}.png" />
<img ng-show="driver" src="img/flags/{{driver.Driver.nationality}}.png" /><br/>
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</div>
</div>
<div class="driver-status">
Country: {{driver.Driver.nationality}} <br/>
Team: {{driver.Constructors[0].name}}<br/>
Birth: {{driver.Driver.dateOfBirth}}<br/>
Biography
</div>
</nav>
<div class="main-content">
<table class="result-table">
<thead>
<tr><th colspan="5">Formula 1 2013 Results</th></tr>
</thead>
<tbody>
<tr>
<td>Round</td> <td>Grand Prix</td> <td>Team</td> <td>Grid</td> <td>Race</td>
</tr>
<tr ng-repeat="race in races">
<td>{{race.round}}</td>
<td><img src="img/flags/{{race.Circuit.Location.country}}.png" />{{race.raceName}}</td>
<td>{{race.Results[0].Constructor.name}}</td>
<td>{{race.Results[0].grid}}</td>
<td>{{race.Results[0].position}}</td>
</tr>
</tbody>
</table>
</div>
</section>
view1.js:
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', [function() {
}]);
angular.module('F1FeederApp', [
'F1FeederApp.services',
'F1FeederApp.controllers',
'ngRoute'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/drivers/:id", {templateUrl: "view1/driver/driver.html", controller: "driverController"}).
otherwise({redirectTo: '/view1'});
}]);
services.js:
angular.module('F1FeederApp.services', [])
.factory('ergastAPIservice', function($http) {
var ergastAPI = {};
ergastAPI.getDrivers = function() {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/driverStandings.json?callback=JSON_CALLBACK'
});
}
ergastAPI.getDriverDetails = function(id) {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/driverStandings.json?callback=JSON_CALLBACK'
});
}
ergastAPI.getDriverRaces = function(id) {
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/2013/drivers/'+ id +'/results.json?callback=JSON_CALLBACK'
});
}
return ergastAPI;
});
angular.module('F1FeederApp.controllers', []).
/* Drivers controller */
controller('driversController', function($scope, ergastAPIservice) {
$scope.nameFilter = null;
$scope.driversList = [];
$scope.searchFilter = function (driver) {
var re = new RegExp($scope.nameFilter, 'i');
return !$scope.nameFilter || re.test(driver.Driver.givenName) || re.test(driver.Driver.familyName);
};
ergastAPIservice.getDrivers().success(function (response) {
//Digging into the response to get the relevant data
$scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;
});
}).
/* Driver controller */
controller('driverController', function($scope, $routeParams, ergastAPIservice) {
$scope.id = $routeParams.id;
$scope.races = [];
$scope.driver = null;
ergastAPIservice.getDriverDetails($scope.id).success(function (response) {
$scope.driver = response.MRData.StandingsTable.StandingsLists[0].DriverStandings[0];
});
ergastAPIservice.getDriverRaces($scope.id).success(function (response) {
$scope.races = response.MRData.RaceTable.Races;
});
});

Use ui-sref instead of href to trigger the state change.
<p>This is the partial for view 1.</p>
<input type="text" ng-model="filterTxn.Driver.givenName" placeholder="Search..."/>
<table>
<thead>
<tr><th colspan="4">Drivers Championship Standings</th></tr>
</thead>
<tbody>
<tr ng-repeat="driver in driversList | filter: filterTxn ">
<td>{{$index + 1}}</td>
<td>
<a ui-sref="/driver/{{driver.Driver.driverId}}">
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</a>
</td>
<td>{{driver.Constructors[0].name}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>

Related

AngularJS search using filter not working

I am trying to search using angularjs filter method but its not working. I am not getting any errors in the console but still the search result is not showing up. Can someone help me on this.
This is my controller.js code:
.controller('SearchController',
[
'$scope',
'dataService',
'$location',
'$routeParams',
function ($scope, dataService, $location, $routeParams){
$scope.searchMovies = [ ];
$scope.searchCount = 0;
var getSearchResult = function (terms) {
dataService.getSearchResult(terms).then(
function (response) {
$scope.searchCount = response.rowCount + ' movies';
$scope.searchMovies = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "All movie Success";
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
if ($routeParams && $routeParams.term) {
console.log($routeParams.term);
getSearchResult($routeParams.term);
}
}
]
);
This is the services.js code:
this.getSearchResult = function (terms) {
var defer = $q.defer(),
data = {
action: 'search',
term: terms
}
$http.get(urlBase, {params: data, cache: true}).
success(function(response){
defer.resolve({
data: response.ResultSet.Result,
rowCount: response.RowCount
});
}).
error(function(err){
defer.reject(err);
});
return defer.promise;
};
This is my app.js code:
. when('/search', {
templateUrl : 'js/partials/search.html',
controller : 'SearchController'
}).
This is the search.html code:
<div>
<label>Search: <input ng-model="searchMovie"></label><br><br><br><br>
</div>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="search in searchMovies | filter:searchMovie">
<td>
{{search.title}}
</td>
<td>
{{search.description}}
</td>
<td>
{{search.name}}
</td>
</tr>
</tbody>
</table>
The search data is being retrieved from the database. I have tested the SQL and it works fine. Just thee problem is in the angularjs server side. Thank you.
You need to give Alias for controller in your app.js file
.when('/search', {
templateUrl : 'js/partials/search.html',
controller : 'SearchController'
controllerAs: 'movies',
});
Now After This in your search.html file pass controllerAs
<div>
<label>Search: <input ng-model="searchMovie"></label><br><br><br><br>
</div>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="search in searchMovies | filter:searchMovie">
<td>
{{movies.search.title}}
</td>
<td>
{{movies.search.description}}
</td>
<td>
{{movies.search.name}}
</td>
</tr>
</tbody>

Angular Js - Cannot read property 'push' of undefined - Error

im making a simple app, that can add a name and a description in a table.
But im getting the error of - Cannot read property 'push' of undefined.
Could some one help me ?
this is my code.
HTML
<div id="main">
<!-- angular templating -->
<!-- this is where content will be injected -->
<div ng-view>
</div>
</div>
JS
var scotchApp = angular.module('scotchApp', ['ngRoute','dx']);
scotchApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode({ enabled: true, requireBase: false });
$routeProvider
// route for the home page
.when('/', {
templateUrl: '/pages/home.html',
controller: 'mainController'
})
.when('/new', {
templateUrl: '/pages/edit.html',
controller: 'newController'
});
})
scotchApp.controller('newController', function ($scope, $location) {
$scope.person = { name: "", description: "" };
$scope.save = function () {
$scope.crew.push($scope.person);
$location.path("/")
}
});
scotchApp.controller('mainController', function ($scope) {
$scope.crew = [
{ name: "Hugo", description: "Programador" },
{ name: "Vitor Lopes", description: "Técnico de Informática" },
{ name: "Pedro Sousa", description: "Webdesigner" },
]
});
HTML - new.html ( page where i have my table)
<table class="table table-striped" style="width: 350px;">
<thead>
<tr>
<td><strong>Nome</strong></td>
<td><strong>Descrição</strong></td>
<td><i class="glyphicon glyphicon-plus"></i></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in crew">
<td>{{person.name}}</td>
<td>{{person.description}}</td>
<td><i class="glyphicon glyphicon-edit"></i></td>
</tr>
</tbody>
</table>
HTML - new.html ( page where i will add my new contact)
<form>
<input ng-model="person.name" placeholder="Enter Name"/><br />
<input ng-model="person.description" placeholder="Enter Description" /><br />
<button ng-click="save()" class="btn-primary">Save</button>
Thank You !!
define your array before push something like so :
$scope.crew = []

Get data from row when clicked and display to editable dialog box

I'm trying to use Angularjs to get data from a row in a table when it is clicked and display it in an editable dialog box. How can I do this? Here's what I have so far:
<table>
<thead>
<tr>
<th>ID No.</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Gender</th>
<th>Time</th>
<th>Date</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="walkin_member in data | filter:searchFilter">
<td><a class="click">{{walkin_member.id}}</a></td>
<td>{{walkin_member.firstname}}</td>
<td>{{walkin_member.lastname}}</td>
<td>{{walkin_member.gender}}</td>
<td>{{walkin_member.time}}</td>
<td>{{walkin_member.datestamp}}</td>
<td>{{walkin_member.type}}</td>
</tr>
</tbody>
</table>
This is my dialog box markup:
<div id="dlgbox">
<div id="dlg-header">Information</div>
<div id="dlg-body">
Firstname <input type="text" value="{{walkin_member.firstname}}"><br/>
Lastname <input type="text" value="{{walkin_member.lastname}}"><br/>
Gender <input type="text" value="{{walkin_member.gender}}"><br/>
Type <input type="text" value="{{walkin_member.type}}"><br/>
</div>
<div id="dlg-footer">
<button onclick="dlgUpdate()">Update</button>
<button onclick="dlgExit()">Exit</button>
</div>
</div>
Here's my controller:
myApp.controller('loglistController', ['$scope', '$http', function ($scope, $http) {
$http.get("../php/loglistajax.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
}]);
the dialog box is hidden, it will just show if the function is triggerd onclick
here's my javascript.
function showDialog(){
var whitebg = document.getElementById("white-background");
var dlg = document.getElementById("dlgbox");
whitebg.style.display = "block";
dlg.style.display = "block";
var winWidth = window.innerWidth;
dlg.style.left = (winWidth/2) - 480/2 + "px";
dlg.style.top = "150px";
}
Add an ng-click event to the anchor tag in each row and pass the current member to the method.
<tr ng-repeat="walkin_member in data | filter:searchFilter">
<td>
<a class="click" href="#"
ng-click="showInEdit(walkin_member)">{{walkin_member.id}}</a>
</td>
</tr>
Now in your controller, Add a new property to hold the selected member and a method called showInEdit()
myApp.controller('loglistController', ['$scope', '$http', function ($scope, $http) {
$scope.data=[];
$scope.selectedMember={ firstname:"",lastname:"",gender:"",type:"" }; //new property
$http.get("../php/loglistajax.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
$scope.showInEdit=function(member){
$scope.selectedMember = member;
};
}]);
And in your model dialog, you will use the selectedMember property.
<div id="dlgbox">
<div id="dlg-header">Information</div>
<div id="dlg-body">
Firstname <input type="text" ng-model="selectedMember.firstname" />
</div>
</div>

Pass a variable from view to controller in Express Angular

I have a view which displays List of my database and it works!
All I want to do is to pass a variable named "search1" from view to server side Controller Thats ALL!
View
<section data-ng-controller="AllsController" data-ng-init="find()">
<div class="page-header">
<h1>Alls</h1>
</div>
<div class="Search">
<select data-ng-model="search1" id="search">
<option value="Model1">Jeans</option>
<option value="Model2">Shirts</option>
</select>
</div>
<br></br><br></br>
<h2>Result Section</h2>
<div class="list-group">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Created</th>
<th>User</th>
<th>Brand</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="all in alls">
<td data-ng-bind="all.created | date:'medium'"></td>
<td data-ng-bind="all.user.displayName"></td>
<td data-ng-bind="all.name"></td>
<td data-ng-bind="all.color"></td>
</tr>
</tbody>
</table>
</div>
Client Controller
angular.module('alls').controller('AllsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Alls', 'Jeans', function($scope, $stateParams, $location, Authentication, Alls, Jeans) {
$scope.find = function() {
$scope.alls = Alls.query();
}; }]);
Service
angular.module('alls').factory('Alls', ['$resource',
function($resource) {
return $resource('alls/:allId', { allId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
Server Controller
exports.list = function(req, res) {
var search1 = req.search1 ;
if (search1 === 'Jeans' )
{
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
res.jsonp(jeans);
});
} }
Server Route
module.exports = function(app) {
var alls = require('../../app/controllers/alls.server.controller');
app.route('/alls')
.get(alls.list);}
I should be able to see Jeans Model when it is chosen but it does not show me Jeans Model
I think I have not passed "search1" to the server Controller properly and I need to change my client Controller or Server Route;
But I do not know how!
Any idea or example would be helpful,
Thanks!
I think you need to change
var search1 = req.search1;
to
var search1 = req.params.search1;

No data over json

I am using angularjs 1.2.8 with grails 2.3.4 backend. I am providing a Restful Api over the grails Resources tag.
I have a view were I load the data:
<div class="container main-frame" ng-app="testapp"
ng-controller="searchController" ng-init="init()">
<h1 class="page-header">Products</h1>
<table class="table">
<thead>
<tr>
<th width="25px">ID</th>
<th>TITLE</th>
<th>PRICE</th>
<th>Description</th>
<th width="50px"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="p in product by $id">
<td>{{p.id}}</td>
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td>{{p.description}}</td>
<!-- ng-show="user.id &&user.id==e.user_id" -->
</tr>
</tbody>
</table>
<!-- ng-show="user.username" -->
<p>
</div>
I am using the searchController to load the data:
testapp.controller("searchController", function($scope, $rootScope, $http, $location) {
var load = function() {
console.log('call load()...');
var url = 'products.json';
if ($rootScope && $rootScope.appUrl) {
url = $rootScope.appUrl + '/' + url;
}
$http.get(url)
.success(function(data, status, headers, config) {
$scope.product = data;
angular.copy($scope.product, $scope.copy);
});
}
load();
});
However in my postgresql db there is data available, but I only get:
and no expection at all:
Any suggestions what I can do to check that?
PS.: Controller is loaded!
UPDATE
Using
<tr ng-repeat="p in product track by p.id">
I am getting an error:
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.8/ngRepeat/dupes?p0=p%20in%20product%20track%20by%20p.id&p1=undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:6:449
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:184:445
at Object.fn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:99:371)
at h.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:100:299)
at h.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:103:100)
at f (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:67:98)
at E (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:71:85)
at XMLHttpRequest.v.onreadystatechange (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:72:133) angular.js:9413
UPDATE2
The json representation looks like that:
[{"class":"com.testapp.Product.BasicProduct","id":1,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":5.0,"title":"Product1"},{"class":"com.testapp.Product.BasicProduct","id":2,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":75.0,"title":"Product2"},{"class":"com.testapp.Product.BasicProduct","id":3,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":50.0,"title":"Product3"},{"class":"com.testapp.Product.BasicProduct","id":4,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":25.0,"title":"Product4"},{"class":"com.testapp.Product.BasicProduct","id":5,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":15.0,"title":"Product5"}]
Fix the ngRepeat syntax:
<tr ng-repeat="p in product track by p.id">

Categories

Resources