unable to repeat collections value using angularjs ng-repeat - angularjs

I was trying to do a webAPI call from AnguarJs. I receive success response "data" object perfectly.When it is passed to HTML page under "ng-repeat" it is not displaying any records.
Following is the one not working
<tr ng-repeat = "cust in Customers">
<td>{{ cust.CustomerName }} </td>
<td>{{ cust.CustomerCode }}</td>
<td>{{ cust.CustomerAmount }}</td>
<td>{{ cust.ProcessDate }}</td>
</tr>
But if i put in this way it will display the 0th index records
<tr ng-repeat = "cust in Customers">
<td>{{cust[0].CustomerName }} </td>
<td>{{cust[0].CustomerCode }}</td>
<td>{{cust[0].CustomerAmount}}</td>
<td>{{cust[0].ProcessDate }}</td>
</tr>
Note : In the below code i split up files in different javascript files and referred in the main html page.Just for your information.
My Fiddle Link : JsFiddle
Please help me in resolve it.
function Utility(){
this.ApplicationVersion = "0.0.1";
this.ApplicationName = "AngularJs First Project";
this.getDate = function () {
var dt = new Date();
return dt.toDateString();
}
this.IsEmpty = function (value) {
if (value.length == 0) {
return false;
}
else {
return true;
}
}
}
function Customer(utility) {
this.CustomerCode = "1001";
this.CustomerName = "Ragu";
this.CustomerAmount = 100;
this.CalculateDiscount = function()
{
return 10;
}
this.ProcessDate = utility.getDate();
}
function Factory()
{
return {
CreateCustomer: function (utility) {
return new Customer(utility);
}
}
}
/// <reference path="Utility.js" />
/// <reference path="Customer.js" />
var myApp = angular.module("myApp", []);
myApp.controller("BindingCode",BindingCode);
myApp.factory("Factory", Factory);
myApp.service("UtilityObj", Utility);
function BindingCode($scope, UtilityObj, Factory,$http)
{
$scope.Customer = Factory.CreateCustomer(UtilityObj);
$scope.Customers = [];
$scope.Utility = UtilityObj;
$scope.Customer.CustomerCode = "1002";
$scope.Customer.CustomerName = "Raman";
$scope.Customer.ProcessDate = UtilityObj.getDate();
$scope.Color = "blue";
$scope.$watch("Customer.CustomerAmount", function () {
if ($scope.Customer.CustomerAmount < 1000) {
$scope.Color = "Red";
}
else {
$scope.Color = "Green";
}
});
$scope.Submit = function()
{
debugger
if ($scope.Utility.IsEmpty($scope.Customer.CustomerAmount)) {
debugger
$http.post("http://localhost:61860/api/Customer", $scope.Customer).then(function(data){
$scope.Customers = data;
debugger
$scope.Customer = {}; // clearing the record
},
function(data)
{
debugger
alert("inside error http call" + data);
}
);
//$http.post("http://localhost:61860/api/Customer", $scope.Customer).
// success(function (data) {
// debugger
// $scope.Customers = data;
// $scope.Customer = {};
//});
}
else {
alert("No Proper Date");
}
}
}
<script src="Scripts/angular.js"></script>
<script src="Customer.js"></script>
<script src="Utility.js"></script>
<script src="app.js"></script>
<body ng-app="myApp">
<div id="CustScreen" ng-controller="BindingCode">
CustomerCode : <input type="text" ng-model="Customer.CustomerCode" id="txtCustomercode" /> <br />
CustomerName : <input type="text" ng-model="Customer.CustomerName" id="txtCustomerName" /> <br />
CustomerDate : <input type="text" ng-model="Customer.ProcessDate" id="txtCustomerDate" /> <br />
CustomerAmount : <input type="text" style="background-color:{{ Color }}" ng-model="Customer.CustomerAmount" id="txtCustomerAmount" /><br />
<br />
{{ Customer.CustomerCode }} <br />
{{ Customer.CustomerName }} <br />
{{ Customer.ProcessDate }}<br />
{{ Customer.CustomerAmount}} <br />
<input type="submit" ng-click="Submit()" id="Submit" />
<table>
<tr>
<td>Name</td>
<td>Code</td>
<td>Amount</td>
<td>ProcessDate</td>
</tr>
<tr ng-repeat = "cust in Customers">
<td>{{cust.CustomerName }} </td>
<td>{{cust.CustomerCode }}</td>
<td>{{cust.CustomerAmount}}</td>
<td>{{cust.ProcessDate }}</td>
</tr>
</table>
</div>
</body>

Try this
$scope.Customers=data[0];

Related

I have a class emp with id name and list of technology type i want to fill it with data coming from dynamic textboxes

i want it to be solved in only angular-js.
<head>
#Scripts.Render("~/bundles/AddEmployee")
</head>
<body ng-app="TruModule">
<div ng-controller="trucontrolleraddemp">
<div style="margin-top:-20px;">
<h1 class="decor">Add Employee</h1>
<form name="emp" novalidate class="warn container" ng-mouseover="hidemessage()">
<div class="col-md-offset-2 row">
<div class="col-sm-4">
<table class="margin">
<tr>
<td>
<label for="id">Id*   :</label>
</td>
<td>
<span>{{id}}</span>
</td>
</tr>
<tr>
<td>
<label for="name">Name* :</label>
</td>
<td>
<input type="text" name="name" ng-model="employee.name" ng-required="true" ng-minlength="2" />
<span ng-show="emp.name.$touched && emp.name.$error.minlength">too short!!!</span>
</td>
</tr>
<tr>
<td>
<label for="role">Role  :</label>
</td>
<td>
<input type="text" name="role" ng-model="employee.role" ng-maxlength="3" />
<span ng-show="emp.role.$touched && emp.role.$error.maxlength">exceed!!!</span>
</td>
</tr>
<tr>
#* <td>
<label for="role">tech  :</label>
</td>
<td>
<input type="text" name="role" ng-model="technology.tech" ng-maxlength="6" />
<span ng-show="emp.role.$touched && emp.role.$error.maxlength">exceed!!!</span>
</td>*#
</tr>
</table>
</div>
<div class="col-sm-4">
<table id="tblEmployee">
<tr>
<td>
<label for="tech">Technologies* :</label>
</td>
<td>
<ul>
<li ng-repeat="techno in technology track by $index">
<input type="text" name="tech" ng-model="employee.technology[$index].tech" ng-required="true" ng-minlength="2" />
</li>
</ul>
</td>
<td>
<span><button class="img" ng-click="addtech()">+</button></span><br/><span><button class="img" ng-click="removetech()">-</button></span>
</td>
</tr>
</table>
</div>
</div>
</form>
<div class="mainloc">
<span><a class="img" href="#!Employee">&lt</a><button class="img position" ng-click="postdata(employee)" value="Submit">+</button> </span>
</div>
<span class="position" ng-hide="IsShown">
<img src="~/reload.gif" />
</span><span style="visibility:hidden"><img src="~/reload.gif" /></span>
<div class="dex alertpos" ng-hide="IsVisible">{{message}}</div>
</div>
<hr style="margin-top:91px;" />
</div>
</body>
i want data to be in the following format. it is the format
accepted by the model employee in controller in webapi.
{
"id":1,
"name":"erk",
"role": "sa",
"technologies":[
{"tech":"Test3"},
{"tech":"Test1"},
]
},
}
the format i am getting is like
this
{"id":4,
"name":"Sam",
"role":"sa",
"technology
":{"0":{"tech":"dfg"},
"1": {"tech":"dfgdfg"}},
}
I have tried using [$index] to make sure that each text box gets a
different value. But since it is returning objects with indexes, I do not
want like that. I want it to be replaced with tech.
/// <reference path="../scripts/angular-route.min.js" />
/// <reference path="../scripts/angular.min.js" />
/// <reference path="../scripts/angular-route.js" />
trumodule.service("idgenerator", function () {
this.idfunc = function () {
return Math.floor(((Math.random()) * 6) + 1);
}
});
var trucontrolleraddemp = function ($scope, $http, $timeout, $route, idgenerator) {
var id = idgenerator.idfunc();
$scope.id = id;
$scope.IsShown = true;
$scope.technology = [];
$scope.addtech = function () {
$scope.technology.push({});
}
$scope.removetech = function () {
$scope.technology.pop({});
}
$scope.postdata = function (data) {
if (data)
$scope.IsShown = false;
data.id = id
var employee = JSON.stringify(data);
$http({ method: "Post", url: '/api/values', data: employee, headers: { 'Content-Type': 'application/json' } })
.then(function (response) {
$scope.IsVisible = false;
$scope.message = response.data;
$timeout(function () {
$route.reload();
}, 2000);
});
}
$scope.message = "Please fill the fields to register a new Employee";
$scope.hidemessage = function () {
$scope.IsVisible = true;
}
$timeout(function () {
$scope.message = "Its mandatory to fill fields with *";
}, 2000);
}
trumodule.controller("trucontrolleraddemp", trucontrolleraddemp);
I have a class employee in that i have fields id, name, role and a list
technologies of type technology, which is another class containing string
field tech, I want data to be filled in that using ng-repeat.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPI_Angular.Models
{
public class Employee
{
public int id;
public string name;
public string role;
//public DateTime DoB;
public List<technology> technologies;
}
public class technology
{
public string tech;
}
}
I have found an alternative answer for my question but really want someone to tell me how can i bring the data at once and that too in the accepted format. Here i am posting my answer.
var trucontrolleraddemp = function ($scope, $http, $timeout, $route, idgenerator) {
var id = idgenerator.idfunc();
$scope.id = id;
$scope.IsShown = true;
$scope.technologies = [];
$scope.addtech = function () {
$scope.minus = true;
if ($scope.technologies.length<3)
$scope.technologies.push({});
}
$scope.removetech = function () {
$scope.technologies.pop({});
if (!$scope.technologies.length)
$scope.minus = false;
}
$scope.postdata = function (employee, technologies) {
if (employee)
$scope.IsShown = false;
employee.id = id
$scope.employee.technologies = [];
angular.forEach(technologies, function (value) {
$scope.employee.technologies.push(value);
});
var employee = JSON.stringify(employee);
$http({ method: "Post", url: '/api/values', data: employee, headers: { 'Content-Type': 'application/json' } })
.then(function (response) {
$scope.IsVisible = false;
$scope.message = response.data;
$timeout(function () {
$route.reload();
}, 2000);
});
}
$scope.message = "Please fill the fields to register a new Employee";
$scope.hidemessage = function () {
$scope.IsVisible = true;
}
$timeout(function () {
$scope.message = "Its mandatory to fill fields with *";
}, 2000);
}
trumodule.controller("trucontrolleraddemp", trucontrolleraddemp);
I am posting only changes that i have done in html.
<td>
<label for="tech">Technologies* :</label>
</td>
<td>
<ul>
<li ng-repeat="techno in technology track by $index">
<input type="text" name="tech" ng-model="employee.technology[$index].tech" ng-required="true" ng-minlength="2" />
</li>
</ul>
</td>
<td>
</td>
<td>
<span><span><button class="img2" ng-click="addtech()">+</button></span><span class="mar-l20"><button class="img2" ng-show=minus ng-click="removetech()">-</button></span></span>
</td>
</tr>
</table>

Angular in electron, slow rendering for large json

I'm currently learning Electron and using AngularJS.
I've my REST api in node and express and my database is MongoDB.
this is my route
router.get('/branch/:branch',function (req,res,next) {
var br = req.params.branch;
var final = [];
db.collection('users').find({"branch": br}, function (err, docs) {
docs.forEach(function (ele) {
console.log(ele['fir_id']);
final.push(ele['fir_id']);
})
db.punch_coll.find(function (err, docs) {
var d = [];
console.log(final);
docs.forEach(function (ele) {
console.log(ele['fir_id']);
if(final.includes(parseInt(ele['fir_id']))) {
ele['date'] = ele['date'].toDateString();
ele['punch_in'] = ele['punch_in'].substring(0, 8);
ele['punch_out'] = ele['punch_out'].substring(0, 8);
d.push(ele);
}
console.log(d);
})
console.log(d);
res.send(d);
})
});
});
punch_coll document
{
_id: 58e21075e0c6800ce8b08d92,
fir_id: '4',
date: 'Mon Apr 03 2017',
punch_in: '14:35:57',
punch_out: ''
}
user document
{
_id: 58e20ee0e0c6800ce8b08d82,
name: 'A B C',
fir_id: 1,
branch: 'CSE',
year: 'SE'
}
HTML and Angular Controller Script
<body ng-app="myApp" ng-controller="myCtrl">
<form class="pure-form">
<strong>Enter FIR-ID</strong> <input type="text" ng-model="fid" ng-
change="change()" class="pure-input-rounded">
</form>
</br>
<div class="pure-g">
<div class="pure-u-8-24" style="border-style: solid;border-
color:lightgrey;">
<header class="w3-container w3-light-grey">
<h2>Fir ID :- {{fid}}</h2>
<h3>Name :- {{user[0].name}} </h3>
</header>
<div class="w3-container">
<h2>Branch :- {{user[0].branch}} </h2>
<hr>
<h2>Academic Year :- {{user[0].year}} </h2>
</div>
</div>
</div>
<form class="pure-form">
<select id="state" ng-model="branch" ng-change="changeBranch()">
<option>CSE</option>
<option>MECH</option>
<option>CIVIL</option>
<option>ENTC</option>
</select>
</form>
<!-- <h2>Fir ID :- {{fid}}</h2>
<h2>Name :- {{user[0].name}} </h2>
<h2>Branch :- {{user[0].branch}} </h2>
<h2>Academic Year :- {{user[0].year}} </h2> -->
<div style="right:0;top:0;position:absolute;font-size:20px;">
<table class="pure-table pure-table-horizontal">
<thead>
<tr>
<th>Fir ID</th>
<th>Date</th>
<th>Punch In</th>
<th>Punch Out</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in name">
<td>{{ x.fir_id }}</td>
<td>{{ x.date }}</td>
<td>{{ x.punch_in }}</td>
<td>{{ x.punch_out }}</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
// You can also require other files to run in this process
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.name;
$scope.user;
$scope.fid;
$scope.branch='CSE';
$scope.change = function() {
//get punches for specific fir_id
$http.get('http://localhost:3000/users/'+$scope.fid)
.then(function(response) {
$scope.user=response.data;
})
//get punches for specific fir_id
$http.get('http://localhost:3000/punch/'+$scope.fid)
.then(function(response) {
console.log(response.status);
$scope.name=response.data;
}, function errorCallback(response) {
$scope.name=null;
});
};
$scope.changeBranch = function(){
//get record as per branch
$http.get('http://localhost:3000/branch/'+$scope.branch)
.then(function(response) {
console.log(response.status);
$scope.name=response.data;
}, function errorCallback(response) {
$scope.name=null;
});
};
});
The table is rendering slow for large json takes 1second it's like it's lagging.
I'm new to this so of course I'm doing something horrible. I think the way I'm using that async functions are bad also but dont know whats making it slow foreach or anything else.
So, after replacing foreach with simple for loop it solved the problem but I don't know whats the exact reason. Anyone had same problem?

Response Data is not binding to table with ng-repeat

I am working on a sample app using angularJS.
I have a service which returns JSON object, I am trying to bind the response to a table.
Controller -
(function () {
var app = angular.module('searchApp', []);
app.config(function ($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['http://localhost:11838/SearchProfiles/get']);
});
var controller = app.controller('searchController', ["$scope", "$http", function ($scope, $http) {
$scope.profileName = "";
$http.get("http://localhost:11838/SearchProfiles/GetAllRuleSets")
.then(function (response) {
$scope.ruleSets = response.data;
});
$scope.searchProfiles = function () {
$http.get("http://localhost:11838/SearchProfiles/GetProfiles?profileName=" + $scope.profileName
+ "&ruleSetName=" + $scope.selectedRuleSet)
.then(function (response) {
$scope.showProfiles = true;
$scope.profiles = response.data;
console.log($scope.profiles);
});
};
$scope.clearForm = function () {
$scope.profileName = "";
$scope.selectedRuleSet = "";
};
}]);
})();
cshtml -
#{
ViewBag.Title = "Search Profiles";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Search Profiles</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
#Scripts.Render("~/Scripts/angular")
#Styles.Render("~/Content/css/scss")
</head>
<body ng-app="searchApp">
<div ng-controller="searchController" id="content">
<label>Profile Name: </label>
<input type="text" name="profileName" ng-model="profileName" /><br />
<label>RuleSet Name: </label>
<select ng-model="selectedRuleSet" ng-options="x for x in ruleSets"></select><br />
<button name="search" ng-click="searchProfiles()">Search</button>
<button name="clear" ng-click="clearForm()">Clear</button>
</div>
<div ng-controller="searchController" id="profilesDiv">
<table>
<tr ng-repeat="x in profiles">
<td>{{ x.ProfileName }}</td>
<td>{{ x.CreationDate }}</td>
</tr>
</table>
</div>
</body>
I am getting back following response -
[{"ProfileName":"Profile3","CreationDate":"1/9/2017"},{"ProfileName":"Profile4","CreationDate":"12/30/2016"}]
but even after setting $scope.profiles I am not seeing table on UI.
I'm fairly new to angular, am I missing something obvious.
Any help is appreciated.
The problem is that you are fetching the data in one scope (the div content where you declare ng-controller="searchController") and then trying to
view the data in another scope (the div profilesDiv where you again declare the ng-controller="searchController").
To solve the problem you need to remove ng-controller="searchController" from the profilesDiv and move the profilesDiv inside the content div.
Like this:
<body ng-app="searchApp">
<div ng-controller="searchController" id="content">
<label>Profile Name: </label>
<input type="text" name="profileName" ng-model="profileName" /><br />
<label>RuleSet Name: </label>
<select ng-model="selectedRuleSet" ng-options="x for x in ruleSets"></select><br />
<button name="search" ng-click="searchProfiles()">Search</button>
<button name="clear" ng-click="clearForm()">Clear</button>
<div id="profilesDiv">
<table>
<tr ng-repeat="x in profiles">
<td>{{ x.ProfileName }}</td>
<td>{{ x.CreationDate }}</td>
</tr>
</table>
</div>
</div>
</body

ngTable Detect Sorting in View

Is there a way to detect whether or not ngTable currently has a sort applied? Binding to the sorting table parameter does not work correctly.
<!--- Never shows---->
<label ng-if="tableParams.$params.sorting === {}">No sort applied</label>
<!--- Never shows---->
<label ng-if="tableParams.$params.sorting() === {}">No sort applied</label>
Oddly enough this simple binding example works as expected:
<label>settings={{ tableParams.$params.sorting }}</label>
When a sort is applied a value of: {"sortColumn":"sortDirection"} appears:
{"Id":"desc"}
or if a sort is not applied:
{}
Any help would be appreciated.
You can do something like this:
var app = angular.module('app', []);
app.controller('myController', function($scope) {
$scope.angular = angular;
$scope.tableParams = {
$params: {
sorting: {}
}
};
$scope.sort = function() {
$scope.tableParams.$params.sorting[1] = true;
};
$scope.unsort = function() {
delete $scope.tableParams.$params.sorting[1];
};
$scope.isSorted = function(tableParams) {
return !angular.equals({}, tableParams.$params.sorting);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myController">
<div ng-show="!isSorted(tableParams)">No sort applied</div>
<button ng-click=sort()>sort</button>
<button ng-click=unsort()>unsort</button>
<br>{{ tableParams }}
</div>
</div>
You can also make the angular object accessible in templates by making it available to the scope.
var app = angular.module('app', []);
app.controller('myController', function($scope) {
$scope.angular = angular;
$scope.tableParams = {
$params: {
sorting: {}
}
};
$scope.sort = function() {
$scope.tableParams.$params.sorting[1] = true;
};
$scope.unsort = function() {
delete $scope.tableParams.$params.sorting[1];
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myController">
<div ng-show="angular.equals({}, tableParams.$params.sorting)">No sort applied</div>
<div>
<button ng-click=sort()>sort</button>
<button ng-click=unsort()>unsort</button>
</div>
<div><br>{{ tableParams }}</div>
</div>
</div>
var app = angular.module('app', []);
app.controller('myController', function($scope) {
$scope.angular = angular;
$scope.tableParams = {
$params: {
sorting: {}
}
};
$scope.sort = function() {
$scope.tableParams.$params.sorting[1] = true;
};
$scope.unsort = function() {
delete $scope.tableParams.$params.sorting[1];
};
$scope.strictlyEqualsEmptyObject = function(obj) {
return {} === obj;
};
$scope.equalsEmptyObject = function(obj) {
return {} == obj;
};
$scope.angularEqualsEmptyObject = function(obj) {
return angular.equals({}, obj);
};
$scope.objectKeysLength = function(obj) {
return Object.keys(obj).length === 0;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myController">
<div>{{ tableParams }}</div>
<div>
<button ng-click=sort()>sort</button>
<button ng-click=unsort()>unsort</button>
</div>
<table>
<th>Not sorted check using:</th>
<tr>
<td>strict </td>
<td>{{ strictlyEqualsEmptyObject(tableParams.$params.sorting) }}</td>
</tr>
<tr>
<td>equals </td>
<td>{{ equalsEmptyObject(tableParams.$params.sorting) }}</td>
</tr>
<tr>
<td>angular </td>
<td>{{ angularEqualsEmptyObject(tableParams.$params.sorting) }}</td>
</tr>
<tr>
<td>Object.keys </td>
<td>{{ objectKeysLength(tableParams.$params.sorting) }}</td>
</tr>
</table>
</div>
</div>

how to reset a filter by leaving it empty?

I have a filter on a list :
<input ng-model="searchFileName" />
<table>
<tr ng-repeat="file in folders | filter:searchFileName">
<td><a ng-click="openFolder(file.name)">{{ file.name }}</a></td>
</tr>
</table>
I would like to clear searchFileName value when I click on a result.
This is openFolder function :
$scope.openFolder = function(name) {
$scope.searchFileName = null;
$http.jsonp($scope.server + '?open=' + encodeURIComponent($scope.buildTreePath()) + '&callback=JSON_CALLBACK').success(function(data){
$scope.folders = data;
});
}
}
I can't empty my filter field, it doesn't work... Where am I wrong ?
just use:
$scope.openFolder = function(name) {
$scope.searchFileName = null;
}
var app = angular.module('app', []);
app.controller('fCtrl', function($scope) {
$scope.folders = [
{
name: "Ala"
}, {
name: "Ata"
}, {
name: "Ara"
}, {
name: "Ama"
}
];
$scope.openFolder = function(name) {
$scope.searchFileName = null;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="fCtrl">
<input ng-model="searchFileName" />
<table>
<tr ng-repeat="file in folders | filter:searchFileName">
<td><a ng-click="openFolder(file.name)">{{ file.name }}</a>
</td>
</tr>
</table>
</div>
</div>

Resources