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;
Related
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>
I have an $ngController that is being used in two views. The first view has an <table> with ng-repeat that lists all my data from the db.
I get the selected object form the table by using get($index) and set it to a $scope variable.
The problem is that when i cannot use this same $scope variable on the other view, because its value is undefined. Both views share the same ng-controller.
My Question is: is the redirection cleaning my $scope? Is there any way i can share this data between pages since my application isn't single page?
Things i tried:
1 - Share data through a factory
2 - Using $rootScope
First View - Table with ng-repeat
<table class="table table-striped">
<thead>
<tr>
<th>CNPJ</th>
<th>Razão Social</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="company in companies | filter:{companyName:searchString}">
<td> {{ company.cnpj }}</td>
<td> {{ company.companyName }}</td>
<td>
Visualizar
<button type="button" class="btn btn-warning btn-xs">Editar</button>
<button type="button" class="btn btn-danger btn-xs">Deletar</button>
</td>
</tr>
</tbody>
</table>
Controller
angular.module("distCad").controller("adminCtlr", function($scope, $http, config, $window, $cacheFactory){
$scope.searchTerm = null;
$scope.hideSearcAlert = true;
$scope.companies = [];
$scope.cache = $cacheFactory('companyCache');
$scope.expireLogin = function(){
localStorage.removeItem("type");
$window.location.href = "/";
}
$scope.getResults = function(){
$scope.searchTerm = true;
$http.get("/api/companies").then(
function successCallback(response){
$scope.companies = response.data;
},
function errorCallback(response){
console.log("aaaa" + response);
}
);
}
$scope.getCompany = function(){
return $scope.cache.get("company");
}
$scope.setCompanyFromTable = function(index){
$scope.cache.put("company", $scope.companies[index]);
}
});
Destination View - Part where i am testing
<div class="container" ng-init="getCompany()">
<div class="row">
<div class="col-md-12">
<h2>Dados da empresa {{cache.get("company").companyName}}</h2>
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>
I'm pretty new to AngularJS and I'm at a loss here.
Right now my MVC program uses Razor to display all the data in my .mdf database (i.e: #Html.DisplayFor(modelItem => item.LastName) ). However, I want to go mostly Angular. I am trying to use ng-repeat to display all of the Model data, but I am not sure how to pass that Model data to the Angular controller and then use it. I have tried serializing the Model to JSON in my ng-init, but I don't think I'm doing it right (obviously).
Here is my code:
// controller-test.js
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope) {
$scope.init = function (firstname) {
$scope.firstname = firstname;
}
});
<!-- Index.cshtml -->
#model IEnumerable<Test.Models.Employee>
#{
ViewBag.Title = "Index";
}
<div ng-app="myModule">
<div ng-controller="myController" ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
<table>
<tr ng-repeat= <!--THIS IS WHERE I'M STUCK -->
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
#Scripts.Render("~/Scripts/angular.js")
I'm not sure exactly what I should be repeating on to get the FirstName from the serialized Model. I feel like I have all the pieces, but just unsure how to connect them.
If you have the key firstName on your Json object like:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
}
You can do it in the following way.
On your controller:
myApp.controller('myController', function ($scope) {
$scope.init = function (employees) {
$scope.employees = employees;
}
});
On your view:
<table>
<tr ng-repeat= "employee in employees">
<td>{{ employee.firstName }}<td>
</tr>
</table>
Thank you to darkstalker_010!
What I was confused was with how my Angular controller file interacted with the view. All I had to do was simply treat my angular {{ }} data in my .cshtml file as if I were trying to access the Model data normally (i.e. model.AttributeName)
So here is the updated, working code:
// controller-test.js
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope) {
$scope.init = function (employees) {
$scope.employees= employees;
}
});
<!-- Index.cshtml -->
#model IEnumerable<Test.Models.Employee>
#{
ViewBag.Title = "Index";
}
<div ng-app="myModule">
<div ng-controller="myController" data-ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Title</th>
<th>Department</th>
<th>Email</th>
</tr>
<tr ng-repeat="e in employees">
<td>{{e.FirstName}}</td>
<td>{{e.LastName}}</td>
<td>{{e.Title}}</td>
<td>{{e.Department.DepartmentName}}</td>
<td>{{e.Email}}</td>
</tr>
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
#Scripts.Render("~/Scripts/angular.js")
Here is what it looks like sans formatting:
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">