Filter function failing to display results - javascript

I have the following function which I wrote to filter data based of user input.
controller
var app = angular.module("viewJSON",[]);
app.controller("viewCtrl",function Hello($scope, $http) {
$http({
method: 'GET',
url: './data.json'
}).then(function (response){
$scope.products = response.data;
},function (error){
console.log("error");
});
var data=[];
$scope.filterData = function ($scope) {
if ($scope.names.length != 0 && $scope.brands.length != 0){
data.push(products.name.includes($scope.names) && products.brand.includes($scope.brands));
}else if($scope.names.length == 0 && $scope.brands.length != 0){
data.push(products.brand.includes($scope.brands));
}else if($scope.names.length != 0 && $scope.brands.length == 0){
data.push(products.name.includes($scope.names));
}
return data;
}
});
HTML
<!DOCTYPE html>
<html ng-app="viewJSON">
<head>
<link rel="stylesheet" href="home-page.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="home-page.js"></script>
</head>
<body ng-controller="viewCtrl">
<div class="wrap">
<div class="search" ng-innit="x=0">
<b>Product Name:</b> <input type="text" ng-model="names" class="searchTerm" ng-keydown="x = x+1"><br>
<b>Product Brand:</b> <input type="text" ng-model="brands" class="searchTerm" ng-keydown="x = x+1">
</div>
</div>
<div>
<table class="resultContent" ng-if="x > 0">
<tr>
<th>Brand</th>
<th>Name</th>
<th>Price</th>
<th>Retailer</th>
<th>Image</th>
</tr>
<tr id="rows" ng-repeat="item in filterData">
<td class="otherCol">{{ item.brand }}</td>
<td class="otherCol">{{ item.name }}</td>
<td class="otherCol">{{ item.price }}</td>
<td class="otherCol">{{ item.retailer }}</td>
<td class="imageCol"><img ng-src="{{ item.image_url}}"></td>
</tr>
</table>
</div>
</body>
</html>
I have played about with this for a while, and to my knowledge the function creates an array based of the users input this array is then displayed using ng-repeat. I have tried using filterBy: filterData, although this gives me the error filter not array which confuses me as the output from filterData is an array. I have a feeling that ng-model is not correctly binding with the values 'names' and 'brands' in the function. A point in the right direction would be appreciated.

The reason you are not seeing any results is your filterData, as filterData is a function and therefore you have to use the following syntax to use it.
ng-repeat="item in filterData()"
notice the parentheses at the end. Also keep in mind that using a function in ng-repeat is not a good practice as it is called on every DOM update and adds alot of unnecessary work. I would strongly recommend that you put the filtered data inside an array and use that array in your ng-repeat.

Related

After redirecting to another page how to use controller and scope data of previous page in angularjs

This is for an assignment. Here table contains book details which contains book name, author, price, ISBN and category. When user click on book name it should redirect to order page displaying book name, author and price.
BookPage.html
<script type="text/javascript" src="book.js">
<body ng-app="mymodule" >
<div ng-controller="myController" >
<table border=2>
<thead>
<tr>
<th>ISBN</th>
<th>NAME</th>
<th>AUTHOR</th>
<th>CATEGORY</th>
<th>PRICE</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books">
<td>{{ book.ISBN }}</td>
<td >{{ book.Name }}</td>
<td>{{ book.Author }}</td>
<td>{{ book.Category }}</td>
<td>{{ book.price }}</td>
</tr>
</tbody>
</table>
**books.js**
var myapp = angular.module('mymodule', []);
myapp.controller("myController", function($scope, $http,$window) {
$http.get("https://api.myjson.com/bins/p4ujn").then(function(response) {
$scope.books = response.data;
$scope.getdetail=function(){
$scope.getbookdetail=this.book;
$window.location.href = "orderpage.html";
}
});
});
Page to be redirected when user click on book name.
orderpage.html
<script type="text/javascript" src="book.js"></script>
<body ng-app="mymodule" >
<div ng-controller="myController" >
{{getbookdetail.Name}}<br>
{{getbookdetail.Author}}
{{getbookdetail.price }}<br>
</div>
</body
This is my code. It display nothing, just a blank page.
You can use a Service or factory to share the data across the controllers.
DEMO
var app = angular.module("clientApp", [])
app.controller("TestCtrl",
function($scope,names) {
$scope.names =[];
$scope.save= function(){
names.add($scope.name);
}
$scope.getnames = function(){
$scope.names = names.get();
}
}
);
app.factory('names', function(){
var names = {};
names.list = [];
names.add = function(message){
names.list.push({message});
};
names.get = function(){
return names.list;
};
return names;
});
<!doctype html>
<html >
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="clientApp">
<div ng-controller="TestCtrl">
<input type="text" ng-model="name">
<button ng-click="save()" > save</button>
</div>
<div ng-init="getnames()" ng-controller="TestCtrl">
<div ng-repeat="name in names">
{{name}}
</div>
</div>
</body>
</html>
Apart from service/factory , you can go for other options like localStorage and rootScope, but those are not recommended ways.
You should use factory/Services, localStorage, routeParams or Child Parent controllers

Angular.js - Redirection is cleaning my $scope(?)

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>

Bind Json Data to HTML TABLE

i am new in angular programming,
i want to bind json data that i get from webservice to the html table,
here is my code :
<!DOCTYPE html>
<html>
<head>
<title>LIST OF USER Sample</title>
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/module.js"></script>
<script>
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function () {
var httpRequest = $http
({
method: 'GET',
url: 'http://10.17.44.236:9090/MobileBootcamp.svc/getalluseravailability'
})
.success(function (data, status) {
debugger;
$scope.people = data;
});
};
$scope.loadPeople();
}
</script>
</head>
<body>
<div ng-app="app">
<div ng-controller="PeopleCtrl" ng-init="loadPeople()">
<table>
<tr>
<th>Id</th>
<th>Availibility</th>
</tr>
<tr ng-repeat="x in people.Datalist[0]">
<td>{{x.UserID}}</td>
<td>{{x.Availability}}</td>
</tr>
<tr>
<td>{{people.DataList[0].UserID}}</td>
<td>{{people.DataList[0].Availability}}</td>
</tr>
<tr>
<td>{{people.DataList[1].UserID}}</td>
<td>{{people.DataList[1].Availability}}</td>
</tr>
</table>
</div>
</div>
<script src="cordova.js"></script>
<script src="js/platformOverrides.js"></script>
<script src="js/index.js"></script>
</body>
</html>
and this is the json from the web service
{"Status":true,"Message":"","Data":null,"DataList":[{"ChangeBy":"Admin","ChangeDate":"\/Date(1439437580137+0700)\/","ChangeNo":2,"CreateBy":"Admin","CreateDate":"\/Date(1439437580137+0700)\/","Availability":true,"LastCheckIn":"\/Date(1439437645420+0700)\/","UserID":"Admin"},{"ChangeBy":"ITK_ABD","ChangeDate":"\/Date(1439398800000+0700)\/","ChangeNo":1,"CreateBy":"ITK_ABD","CreateDate":"\/Date(1439398800000+0700)\/","Availability":false,"LastCheckIn":"\/Date(1439398800000+0700)\/","UserID":"ITK_ABD"}]}
i already try the "ng-repeat" but it didnt work,
the data is like Data --> DataList--> [0] --> userid,availability,etc...
thx in advance
You don't need the [0]. Your ng-repeat is here to get all elements of the list. You just have to give your list, not the index and angular will do the job.
<tr ng-repeat="x in people.DataList">
Do as following -
<tr ng-repeat="x in people.Datalist">
<td>{{x.UserID}}</td>
<td>{{x.Availability}}</td>
</tr>
as you have array of objects in Datalist, you should iterate DataList instead of DataList[0]
No need for the [0]. we don't want to loop through your first object, So just people.DataList will do the job. It will loop through all objects inside that array .
<tr ng-repeat="x in people.DataList">
<td>{{x.UserID}}</td>
<td>{{x.Availability}}</td>
</tr>
You are trying to repeat object here:
<tr ng-repeat="x in people.Datalist[0]">
You can repeat only on Array data type. So you must do this like that:
<tr ng-repeat="x in people.Datalist">

pass dom object to processing function in angularjs

In the following code, I am trying to pass the table cell (as a DOM object) to the function, but this doesn't mean the DOM object for the table cell, it appears that it refers to the $scope. Any idea how to do this?
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr >
<td ng-click="dum();">ONE</td>
<td>TWO</td>
</tr>
<tr ng-repeat="x in names">
<td ng-click="dum(this);">{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
obj1 = "haha";
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {$scope.names = response.records;});
$scope.dum = function(x) { obj1 = x; console.log(x); }
});
</script>
</body>
</html>
In angular, you should always code against your data. Coding against the DOM is unnecessary in all but the most extreme edge cases, and when it is necessary, it's usually best done in a directive, where you can control how the rest of the angular app is updated.
In your case, you don't need to access the DOM, or the element, or even an event. You already have all the information you need in order to handle your code with the data.
<tr ng-repeat="x in names">
<td ng-click="dum(x);">{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
and in the controller:
$scope.dum = function(x) { console.log(x); }
You could, probably, do this:
In your HTML
<td ng-click="dum($event);">{{ x.Name }}</td>
In your Javascript
$scope.dum = function(e) { obj1 = e.target; console.log(x); }
//e.target will be the clicked element.
I would not recommend accessing the DOM from a controller, but you can use the $event.target. Here's a plunker example: http://plnkr.co/edit/wFdnPJVa7BHOcvkPqNNT?p=preview
angular.module('Test', [])
.controller('testCtrl', ['$scope', function($scope)
{
$scope.myFunc = function(e)
{
console.dir(e.target);
}
}]);
And the HTML
<body ng-app="Test">
<div ng-controller="testCtrl">
<button ng-click="myFunc($event)">Click Me</button>
</div>
</body>

How do I add each new element in table to top of table when each element is dynamically created from server using angularJS?

In the following code, I am creating a table that uses AngularJS to grab information from a server and adds each item to a table using 'ng-repeat'.
<table class=" table table-striped" id="eventTable">
<thead>
<tr>
<th>Index</th>
<th>Time</th>
<th>Description</th>
<th>Source</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="event in eventslist">
<tr>
<td>{{event.idx}}</td>
<td class="text-left" nowrap>
{{event.srvTime | date :'yyyy-MM-dd HH:mm:ss'}}
</td>
<td class="text-left">
<a data-ui-sref="events.details({edIdx: event.idx})">{{event.desc}}</a>
</td>
<td class="text-left" nowrap>
{{event.s0.id}}
</td>
</tr>
</tbody>
</table>
I have polling set up on the web page from the javascript controller(see below) so it stays near 'real-time'. I need each new item coming in to be added to the top of the table, how do I do this, should it be in the controller or can I do it straight from the HTML file? Thanks!
$scope.latestEventIndex = 0;
var poll;
eventsFactory.getEvents()
.success(function (result) {
angular.forEach(result.v, function (d) {
$scope.eventslist.push(d);
if (d.idx > $scope.latestEventIndex) {
$scope.latestEventIndex = d.idx;
}
});
$rootScope.eventslist = $scope.eventslist;
})
.error(function (error) {
$scope.status = 'Unable to get events: ' +error.message;
console.log($scope.status);
});
poll = $interval(function() {
eventsFactory.getLatestEvents($scope.latestEventIndex)
.success(function (result) {
angular.forEach(result.v, function (d) {
$scope.eventslist.push(d);
if (d.idx > $scope.latestEventIndex) {
$scope.latestEventIndex = d.idx;
}
});
$rootScope.eventslist = $scope.eventslist;
})
.error(function (error) {
$scope.status = 'Unable to get events: ' + error.message;
console.log($scope.status);
});
}, 1000);
Since your array does not appear to be sorted, you can simply insert the new items into the $scope.eventlists array using Array.splice. Here's a plunker:
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
</head>
<body ng-controller="mycon">
<h1>{{test}}</h1>
<div>
<div ng-repeat="item in list">{{item}}</div>
</div>
<input ng-model="newItem" />
<button ng-click="addItemAtTopOfList()">Add</button>
<script>
var app = angular.module('myapp', []);
app.controller('mycon', function($scope){
$scope.list = [];
$scope.addItemAtTopOfList = function(){
$scope.list.splice(0, 0, $scope.newItem);
$scope.newItem = "";
}
});
</script>
</body>
</html>
Let me know if that doesn't answers your question sufficiently.

Categories

Resources