ng-repeat not working in MEAN stack - angularjs

I am new to MEAN stack and i was trying to make a simple contact app. But ng-repeat in my index.html is not working. Here is my code. Files are according to default file structure provided by Express
index.html
<html ng-app="myApp" xmlns:ng="http://www.w3.org/1999/xhtml">
<head>
<title>First Application x</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"> </script>
</head>
<body>
<div class="container" ng-controller="AppCtrl">
<h1>Phone Directory</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control" type="text" placeholder="Enter name"></input></td>
<td><input class="form-control" type="text" placeholder="Email"></input></td>
<td><input class="form-control" type="text" placeholder="Phone No." ></input></td>
<td><button class="btn btn-danger">Add Contact</button></td>
</tr>
<tr ng-repeat="contact in contactlist">
<td class="info">{{ contact.name }}</td>
<td class="info">{{ contact.email }}</td>
<td class="info">{{ contact.phone }}</td>
<td class="info">{{ contact.phone }}</td>
</tr>
</tbody>
</table>
</div>
<script src="/javascripts/controllers/controller.js"></script>
</body>
</html>
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl',['$scope', '$http', function($scope, $http){
$http.get('/contactlist').success(function(response){
$scope.contactlist = response;
console.log(response);
console.log("Hello World from controller");
});
}]);
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: '' });
});
router.get('/contactlist',function(req,res){
person1={
name: 'Tim',
email: 'Tim#gmail.com',
phone: '111 111 -1111'
};
person2={
name: 'Tim cook',
email: 'timcook#gmail.com',
phone: '222 111 -1111'
};
person3={
name: 'Tim Baron',
email: 'barrontim#gmail.com',
phone: '222 333 -1111'
};
var contactlist=[person1,person2,person3];
res.json(contactlist);
});
module.exports = router;

Alright!!
From express app you are passing JSON String so when you receive in ajax call it is JSON String and you need to decode into object.It can be done using JSON.parse() function.
Replace your line with below one
$scope.contactlist = JSON.parse(response);
Hope this solves your problem.

Related

Why data not showing on page in Angular JS

Recently my page was showing data but from yesterday suddenly its now showing. I am confused what I have done wrong. I checked properly and everything is working fine.
Here is code on UI-
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<head runat="server">
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="script.js"></script>
<script src="EmployeeServices.js"></script>
</head>
<body>
<form id="form1" ng-controller="EmpCtrl" ng-submit="save()">
<table border="1" style="text-align: center; margin-left: 410px;">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
<th>Gender</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{employee.Name}}</td>
<td ng-bind="employee.Age"></td>
<td ng-bind="employee.City"></td>
<td>{{employee.Gender && "Male" || "Female"}}</td>
<td>Edit </td>
<td>Delete </td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Code of Controller-
var app = angular.module('myApp', ['ngRoute']);
app.controller('EmpCtrl', function ($scope, $http, fetchEmpService) {
$http.get("EmpWebService.asmx/GetEmp")
.then(function (response) {
$scope.employees = response.data;
});
}
I also checked and realized that controller is receiving the data in object form but its not displaying on UI
I think you missed the "/" at the beginning of 'get' URL.
var app = angular.module('myApp', ['ngRoute']);
app.controller('EmpCtrl', function ($scope, $http, fetchEmpService) {
$http.get("/EmpWebService.asmx/GetEmp")
.then(function (response) {
$scope.employees = response.data;
});
}
Please verify.

Bootstrap fails with AngularJS (and having first row being different)

Trying to learn AngularJS and a hole bunch of frameworks at the same time (doomed to go wrong).
I got this far, but have some issues with the bootstrap not working..
<!DOCTYPE html>
<html ng-app="">
<head>
<meta charset="utf-8" />
<title>Learning firebase and angularJS</title>
<script data-require="moment.js#*" data-semver="2.10.2" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script data-require="chance#*" data-semver="0.5.3" src="http://chancejs.com/chance.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.4.1/firebase.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body style="margin:20px" ng-controller="employeeCtrl">
<div class="">
<button class="btn btn-default" ng-click="saveEmployee()">
Save
<span class="glyphicon glyphicons-ok"></span>
</button>
</div>
<div class="">
<table class="table">
<thead class="thead-inverse">
<tr>
<th>Datetime</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="label label-primary" id="datetime"></div>
</td>
<td>
<label>Employee Name</label>
<input type="text" ng-model="employeeName" />
</td>
<td>
<label>Employee Age</label>
<input type="number" ng-model="employeeAge" />
</td>
</tr>
</tbody>
</table>
<table class="table table-striped">
<thead>
<tr>
<th>Datetime</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody ng-repeat="employee in employees" ng-class-odd="oddRow">
<tr>
<td>{{employee.timestamp}}</td>
<td>{{employee.employeeName}}</td>
<td>{{employee.employeeAge}}</td>
</tr>
</tbody>
</table>
</div>
<script>
function employeeCtrl($scope) {
refresh = function() {
$scope.employeeName = new Chance().name();
$scope.employeeAge = new Chance().age();
}
$scope.employees = {};
refresh();
$scope.myData = new Firebase("https://hello-firebase-world.firebaseio.com/Employees");
$scope.saveEmployee = function() {
date = moment(new Date())
dateStr = date.format('YYYY.MM.DD') + " # " + date.format("LTS");
$scope.myData.push({employeeName: $scope.employeeName, employeeAge: $scope.employeeAge, timestamp: dateStr});
refresh();
};
$scope.myData.on('value', function(snapshot){
$scope.employees = snapshot.val();
$scope.$apply(); // temp. solution
});
};
</script>
<script>
var datetime = null, date = null;
moment.locale('da');
var update = function() {
date = moment(new Date())
dateStr = date.format('YYYY.MM.DD') + " # " + date.format("LTS");
datetime.html(dateStr);
};
$(document).ready(function() {
datetime = $('#datetime')
update();
setInterval(update, 1000);
});
</script>
</body>
</html>
http://plnkr.co/edit/MA52T3?p=preview
Now there should appear a striped table and a glyphicon at the save button.. But there is not.. Any help would be appreciated.
Bonus angular table row questions
I first tried to make the input part of the first row and the do a angular for-loop, but somehow this doesn't work..
<!DOCTYPE html>
<html ng-app="">
<head>
<meta charset="utf-8" />
<title>Learning firebase and angularJS</title>
<script data-require="moment.js#*" data-semver="2.10.2" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script data-require="chance#*" data-semver="0.5.3" src="http://chancejs.com/chance.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.4.1/firebase.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body style="margin:20px" ng-controller="employeeCtrl">
<div class="">
<button class="btn btn-default" ng-click="saveEmployee()">
Save
<span class="glyphicon glyphicons-ok"></span>
</button>
</div>
<div class="">
<table class="table">
<thead class="thead-inverse">
<tr>
<th>Datetime</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="label label-primary" id="datetime"></div>
</td>
<td>
<label>Employee Name</label>
<input type="text" ng-model="employeeName" />
</td>
<td>
<label>Employee Age</label>
<input type="number" ng-model="employeeAge" />
</td>
</tr>
<span ng-repeat="employee in employees">
<tr>
<td>{{employee.timestamp}}</td>
<td>{{employee.employeeName}}</td>
<td>{{employee.employeeAge}}</td>
</tr>
</span>
</tbody>
</table>
</div>
<script>
function employeeCtrl($scope) {
refresh = function() {
$scope.employeeName = new Chance().name();
$scope.employeeAge = new Chance().age();
}
$scope.employees = {};
refresh();
$scope.myData = new Firebase("https://hello-firebase-world.firebaseio.com/Employees");
$scope.saveEmployee = function() {
date = moment(new Date())
dateStr = date.format('YYYY.MM.DD') + " # " + date.format("LTS");
$scope.myData.push({employeeName: $scope.employeeName, employeeAge: $scope.employeeAge, timestamp: dateStr});
refresh();
};
$scope.myData.on('value', function(snapshot){
$scope.employees = snapshot.val();
$scope.$apply(); // temp. solution
});
};
</script>
<script>
var datetime = null, date = null;
moment.locale('da');
var update = function() {
date = moment(new Date())
dateStr = date.format('YYYY.MM.DD') + " # " + date.format("LTS");
datetime.html(dateStr);
};
$(document).ready(function() {
datetime = $('#datetime')
update();
setInterval(update, 1000);
});
</script>
</body>
</html>
http://plnkr.co/edit/x6fSbG?p=info
There is a typo in the bootstrap-part. Change it to:
<span class="glyphicon glyphicon-ok"></span>
Bonus-question: Simply remove the wrapping <span>:
<tbody>
<tr>
<td>
<div class="label label-primary" id="datetime"></div>
</td>
<td>
<label>Employee Name</label>
<input type="text" ng-model="employeeName" />
</td>
<td>
<label>Employee Age</label>
<input type="number" ng-model="employeeAge" />
</td>
</tr>
<tr ng-repeat="employee in employees" >
<td>{{employee.timestamp}}</td>
<td>{{employee.employeeName}}</td>
<td>{{employee.employeeAge}}</td>
</tr>
</tbody>
The glyphicons-ok doesn't exist in your stylesheets, use glyphicon-ok instead.
For your striped table, you're generating all oddRows, shouldn't they be alternating with evenRows...
About button u have mistake there. Change:
<span class="glyphicon glyphicon-ok"></span>
About include angular. This example structure will work:
<!doctype html>
<html ng-app='project'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<base href="/">
</head>
<body>
<ng-view></ng-view>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-resource.min.js"></script>
<script src="app.js" type="text/javascript"></script>
<script src="controllers/main_controller.js" type="text/javascript"></script>
</body>
</html>

AngularJS Filter (Function and input search together)

I want to use filter function and input search at the same time by using AngularJS. I can able to do with multiple functions. But I'm getting some errors while I add an textbox for search. Is there any way to do this? I tried some ways but no one did not work.
Thanks in advance.
Example code is below
var app = angular.module("app", []),
url = "http://www.filltext.com/?rows=50&pretty=true&fName={firstName}&age=[18,19,20,21]";
app.controller("controller", function($scope, $http) {
$http.get(url)
.success(function(resp) {
$scope.list = resp;
});
$scope.filterAge = function(item) {
return item.age > 19;
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<meta charset="utf-8">
<title>AngularJS Filter</title>
</head>
<body ng-controller="controller">
<div class="container">
<br>
<input type="text" ng-model="search" placeholder="Search..." />
<table class="table table-striped">
<thead>
<th>Name</th>
<th>Age</th>
</thead>
<tbody>
<tr ng-repeat="item in list | filter: filterAge">
<td>{{ item.fName }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
You should add custom filter to angular module instead adding filter function to your controller. This is the example:
CustomFilter:
.filter('filterByAge', function filterByAge() {
return function(array, age) {
var filteredArray = [];
angular.forEach(array, function(item) {
if (item.age > age) {
filteredArray.push(item);
}
});
return filteredArray;
}
});
HTML
<input type="text" ng-model="search" placeholder="Search..." />
<table class="table table-striped">
<thead>
<th>Name</th>
<th>Age</th>
</thead>
<tbody>
<tr ng-repeat="item in list | filter: search | filterByAge:19">
<td>{{ item.fName }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
$scope.$watch('search', function (data) {
//sorting logic
})
Watcher is waiting for any action taken on search filed then the function is executed.

Pagination in angular js

I am getting the data from database via http post call and rendering the table. Well the implementation code looks fine however, the pagination doesn't seem to work.
I implemented it according to my requirement and I get the response which I can see in chrome console. What could be wrong with the pagination as I am not able to see any pagination buttons.
Here's the code:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>The Single Page Blogger</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script data-require="ui-bootstrap#*" data-semver="0.12.1" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.min.js"></script>
<script src="<%=request.getContextPath()%>/js/module.js"></script>
<link rel="stylesheet" href="<%=request.getContextPath()%>/style2.css" />
<script>
//Get table from Server and do pagination
app.controller("tableController", function ($scope, $http) {
$scope.filteredTodos = []
, $scope.currentPage = 1
, $scope.numPerPage = 10
, $scope.maxSize = 5;
$scope.getTable = function () {
$scope.customerTable = [];
$http.get('<%=request.getContextPath()%>/GetTable.do').success(function (data)
{
$scope.customerTable = data;
});
};
$scope.getTable();
$scope.$watch("currentPage + numPerPage", function () {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.customerTable.slice(begin, end);
});
});
</script>
</head>
<body>
<div class="container" id="main"><br/><br/>
Search: <input type="text" ng-model="search" placeholder="Search">
<div ng-controller="tableController">
<table class="table table-striped table-hover table-bordered">
<tr>
<th style="font-size: 13.3px">Card number</th>
<th style="font-size: 13.3px">First name</th>
<th style="font-size: 13.3px">Opening balance</th>
<th style="font-size: 13.3px">Withdrawal</th>
<th style="font-size: 13.3px">Deposit</th>
<th style="font-size: 13.3px">Closing balance</th>
<th style="font-size: 13.3px">Tx date</th>
<th style="font-size: 13.3px">Usage type</th>
</tr>
<tr ng-repeat="data in customerTable| filter: search">
<td>{{data.CARD_NUMBER}}</td>
<td>{{data.FIRST_NAME}}</td>
<td>{{data.OPENING_BALANCE}}</td>
<td>{{data.WITHDRAWAL}}</td>
<td>{{data.DEPOSIT}}</td>
<td>{{data.CLOSING_BAL}}</td>
<td>{{data.TXDATE}}</td>
<td>{{data.USAGE_TYPE}}</td>
</tr>
</table>
<pagination
ng-model="currentPage"
total-items="customerTable.length"
max-size="maxSize"
boundary-links="true">
</pagination>
<br/><br/><br>
</form>
</div>
</div>
</body>
</html>
Here's the plunker: http://plnkr.co/edit/eNgT4bVroGIla4EOdkNZ?p=preview
Module:
var app = angular.module('myApp', ['ui.bootstrap']);
Try this,
<tr ng-repeat="data in filteredTodos| filter: search">
<td>{{data.CARD_NUMBER}}</td>
<td>{{data.FIRST_NAME}}</td>
<td>{{data.OPENING_BALANCE}}</td>
<td>{{data.WITHDRAWAL}}</td>
<td>{{data.DEPOSIT}}</td>
<td>{{data.CLOSING_BAL}}</td>
<td>{{data.TXDATE}}</td>
<td>{{data.USAGE_TYPE}}</td>
</tr>
You should be iterating filteredTodos instead of customerTable

ng-repeat doesn't repeat after changing the value

At first i get the data in the begining but after posting some new students i want the array to update and it updates but table doesn't and i dont know why .It suppose to be like this or what?
This is the html
<!DOCTYPE html>
<html lang="en" ng-app="ang">
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="bootstrap.min.css" />
<title>Angular Practice </title>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<style>
div{
overflow:auto;
margin:5px;
}
</style>
</head>
<body ng-controller="TableController as bc">
<div style="margin:5px auto;width:810px">
<div style="width:250px;float:left;">
<form name="forma" novalidate ng-submit="forma.$valid&&bc.sendmes()">
<table class="table table-responsive table-hover">
<tr>
<th colspan="2">Add a new Student</th>
</tr>
<tr>
<td>Name</td>
<td><input type="text" ng-model="bc.telebe.name" class="input-sm" required /></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" ng-model="bc.telebe.surname" class="input-sm" required /></td>
</tr>
<tr>
<td>Age</td>
<td><input type="number" ng-model="bc.telebe.age" class="input-sm" required /></td>
</tr>
<tr>
<th colspan="2"><input type="submit" value="Submit" class="btn-sm" /></th>
</tr>
</table>
</form>
</div>
<div style="width:550px;">
<table ng-controller="TableController as bc" class="table table-responsive table-striped table-bordered table-hover">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
</tr>
<tr ng-repeat="telebe in bc.telebeler">
<td>{{telebe.name}}</td>
<td>{{telebe.surname}}</td>
<td>{{telebe.age}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
This is app.js
app=angular.module("ang",[ ]);
app.controller("TableController",function($http){
var bu = this;
this.telebe = {}
bu.telebeler = [ ];
$http.get("getjson.php").success(function(data){
bu.telebeler = data;
});
this.sendmes=function(){
$http.post("getjson.php",this.telebe).success(function(data){
bu.telebeler = data;
console.log(bu.telebeler);
bu.telebe = {};
});
};
});
This is the getjson.php and this file is clear no problem with php
<?php
require("config.php");
header("Content-type:text/json");
if($s = file_get_contents("php://input")){
$ar=json_decode($s,true);
$name = htmlspecialchars($ar['name']);
$surname = htmlspecialchars($ar['surname']);
$age = htmlspecialchars($ar['age']);
mysql_query("INSERT INTO telebe(name,surname,age) VALUES('$name','$surname','$age')");
};
$tema = mysql_query("SELECT * FROM telebe");
$array = array();
while($sira = mysql_fetch_assoc($tema))$array[]=$sira;
echo json_encode($array);
?>
Remove ng-controller="TableController as bc" directive from the table tag. The controller is already defined in body.
Currently, you have two controllers with different scopes, each of them sending its own HTTP request to get the initial data. When you are changing the data, only the outer controller is updated but you are reading them from the inner controller. Removing the inner controller will fix the problem.
You should insert $scope to your controller and define objects for view on the scope rather then on the controller:
app.controller("TableController",function($scope, $http){
$scope.telebe = {};
$scope.telebeler = [];
...
}
and then in html you should point to the scope like this:
<tr ng-repeat="t in telebeler">
That should make it work.

Resources