Angular ng-repeat does not display data (only at 1st use) - javascript

UPDATE: It was because not setting the values for $scope.quantity
I have 3 places where I should ng-repeat 3 different data sources.
I use 3 controllers, from which only the 1st one displays data. The other two can console.log the data, but do not display it.
I really can't understand why everything works for the 1st set of data, but not for the rest, even though the code is pretty much the same for all of them.
js
//this is working
function publisherController($scope, $http) {
//$scope.sortType = 'name'; // set the default sort type
//$scope.sortReverse = false; // set the default sort order
$scope.searchPublisher = ''; // set the default search/filter term
$http.get("/ServiceProxy.aspx?apiPath=api/path1")
.then(function (response) {
$scope.pubNames = response.data;
console.log(JSON.stringify($scope.pubNames));
});
$scope.quantity = 5;
};
// this is not working
var formatController = function ($scope, $http) {
//$scope.sortType = 'name'; // set the default sort type
//$scope.sortReverse = false; // set the default sort order
$scope.searchFormat = ''; // set the default search/filter term
$http.get("/ServiceProxy.aspx?apiPath=api/demand/path2")
.then(function (response) {
$scope.formatNames = response.data;
console.log($scope.formatNames);
});
};
//this is not working
function distributorController($scope, $http) {
//$scope.sortType = 'name'; // set the default sort type
//$scope.sortReverse = false; // set the default sort order
$scope.searchDistributor = ''; // set the default search/filter term
$http.get("/ServiceProxy.aspx?apiPath=api/path3")
.then(function (response) {
$scope.distributorNames = response.data;
console.log(JSON.stringify($scope.distributorNames));
});
};
html
<div class="row" ng-app>
<-- This is working -->
<div ng-controller="publisherController">
<table class="table table-bordered table-striped">
<tbody id="format">
<tr ng-repeat="roll in pubNames | orderBy:sortType:sortReverse | filter:searchPublisher | limitTo:quantity">
<td><input type="checkbox" id="myCheck">{{roll}}</td>
</tr>
</tbody>
</table>
</div>
<-- This is NOT working -->
<div ng-controller="formatController">
<table class="table table-bordered table-striped">
<tbody id="format">
<tr ng-repeat="f in formatNames | orderBy:sortType:sortReverse | filter:searchDistributor | limitTo:quantity">
<td><input type="checkbox" id="myCheck">{{f}}</td>
</tr>
</tbody>
</table>
</div>
<-- This is NOT working -->
<div ng-controller="distributorController">
<table class="table table-bordered table-striped">
<tbody id="distributor">
<tr ng-repeat="d in distributorNames | orderBy:sortType:sortReverse | filter:searchDistributor | limitTo:quantity">
<td><input type="checkbox" id="myCheck">{{d}}</td>
</tr>
</tbody>
</table>
</div>
</div>

Related

My view is not being rendered (ASP. NET / Angular)

I have a controller that is sending an array with json objects.
Instead of showing me the view, only the contents of the array are shown in the browser.
thank you.
My controller:
public JsonResult IndexJson()
{
var equipas = db.Equipas.Select(t => new { Nome = t.Nome, Abreviatura = t.Abreviatura, Country = t.Country }).ToList();
return Json(equipas, JsonRequestBehavior.AllowGet);
}
My view:
#{
ViewBag.Title = "getAll";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-app="ruyApp" ng-controller="equipasCtrl">
<table class="table">
<tr>
<th>
Nome
</th>
<th>
País
</th>
<th>
Abreviatura
</th>
</tr>
<tr ng-repeat="x in myData">
<td>
{{x.Nome}}
</td>
<td>
{{x.Country}}
</td>
<td>
{{x.Abreviatura}}
</td>
</tr>
</table>
</div>
<script src="~/Scripts/AngularScripts.js"></script>
My script:
var app = angular.module('ruyApp', []);
app.controller('equipasCtrl', function ($scope, $http) {
$http.get('/Equipas/IndexJson').then(function (response) {
$scope.myData = response.data;
$scope.statustext = response.statusText;
$scope.statuscode = response.status;
});
});
Browser output:
[{"Nome":"Real Madrid","Abreviatura":"RM","Country":"Espanha"},{"Nome":"Benfica","Abreviatura":"BEN","Country":"Portugal"},{"Nome":"FC Porto","Abreviatura":"FCP","Country":"Portugal"},{"Nome":"Barcelona","Abreviatura":"BAR","Country":"Espanha"},{"Nome":"PSG","Abreviatura":"PSG","Country":"França"},{"Nome":"Charlotte Hornets","Abreviatura":"CHA","Country":"EUA"},{"Nome":"Boston Celtics","Abreviatura":"BOS","Country":"EUA"},{"Nome":"Indiana Pacers","Abreviatura":"IND","Country":"EUA"}]
I think that when you return other result than ViewResult, the ViewEngine is not triggered and no view is returned. I would return the json as a model to the view: ex. return this.View(jsonEquipas) Or pass the equipas as a property to the view model you pass to the view.
I do not know why that code does not work. I solved the question by putting the ng-init directive with the parse of the model.
View
<div ng-app="ruyApp" ng-controller="equipasCtrl" ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
</div>
Script
app.controller('equipasCtrl', function ($scope) {
$scope.init = function (equipas) {
$scope.myData = equipas;
});

orderBy not working with pagination and filters

<table>
<thead>
<tr>
<th class="col-md-3" ng-click="sortDirection = !sortDirection">Created At</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="food in foods | filter:foodFilter | itemsPerPage:pageSize | orderBy:'created_at_date'">
<td class="col-md-"> {{food.created_at_date}} </td>
</tbody>
</table>
<dir-pagination-controls
max-size= 7
boundary-links="true">
</dir-pagination-controls>
This is only a snippet of my code but its too large to put up. Everything is working except only some of the created_at_date is in order. When I click on a different filter to add in or remove data depending on that filter, only some of it is entered into the correct place. My main question is: is there someway to sort all of the dates properly while still allowing the everything else function as well? All help is welcome, Thanks
(function () {
"use strict";
App.controller('foodsController', ['$scope'],
function($scope) {
$scope.sortDirection = true;
In your controller you can add the method to order the array before you loop over them.
Assuming your foods array has an array of objects, each with a key of created_at_date and a value:
App.controller('foodsController', function($scope) {
$scope.foods = [{
created_at_date: 6791234
}, {
created_at_date: 9837245
}, {
created_at_date: 1234755
}];
// create a method exposed to the scope for your template.
$scope.orderBy = function(key, array) {
// now you've received the array, you can sort it on the key in question.
var sorted = array.sort(function(a, b) {
return a[key] - b[key];
});
return sorted;
}
});
Now on your template, you have a method available to sort your values for you:
<table>
<thead>
<tr>
<th class="col-md-3" ng-click="sortDirection = !sortDirection">Created At</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="food in orderBy('created_at_date', foods) | filter:foodFilter | itemsPerPage:pageSize">
<td class="col-md-"> {{food.created_at_date}} </td>
</tr>
</tbody>
</table>
The orderBy method which we've created on your controller returns an array, but it's just sorted by the key that's sent in as the first argument of the function. The second argument is the original array you're trying to sort.
At least this way you can check if you remove all your other filters to see if it's ordered correctly, if then after you add them back in it changes it's because those filters are also changing the order.

Formatting data before render it

I am displaying some data in the view, but I need to formatted first, I was doing something like
val.toFixed(2) and that is OK, it works but the problem is that val sometimes comes with letters, and toFixed(2) is not taking that into account so is not displaying the letters.
So I need something that takes into account letters and numbers, the letters don't have to change, only the numbers which comes like 234235.345345435, and obviously I need it like this 234235.34.
Here is some of the code I am using
<table>
<tr>
<th ng-repeat='header in headers'>{{header.th}}</th>
</tr>
<tr>
<td ng-repeat='data in headers'>
<div ng-repeat='inner in data.td'>
<span ng-repeat='(prop, val) in inner'>{{val.toFixed(2)}}</span>
</div>
</td>
</tr>
</table>
and in the controller
$scope.LoadMyJson = function() {
for (var s in myJson){
$scope.data.push(s);
if ($scope.headers.length < 1)
for (var prop in myJson[s]){
prop.data = [];
$scope.headers.push({th:prop, td: []});
}
}
for (var s in $scope.data){
for (var prop in $scope.headers){
var header = $scope.headers[prop].th;
var data = myJson[$scope.data[s]][header];
$scope.headers[prop].td.push(data);
console.log($scope.headers[prop].td);
}
}
};
and I prepared this Fiddle
the way it is right now, is displaying the table properly, but as you see, the table is missing the name, it is because of the toFixed method.
So, what can I do ?
Create a custom filter to use on your template.
<table>
<tr>
<th ng-repeat='header in headers'>{{header.th}}</th>
</tr>
<tr>
<td ng-repeat='data in headers'>
<div ng-repeat='inner in data.td'>
<span ng-repeat='(prop, val) in inner'>{{val|formatValue}}</span>
</div>
</td>
</tr>
</table>
angular.module('whatever').filter('formatValue', function () {
return function (value) {
if (isNaN(parseFloat(value))) {
return value;
}
return parseFloat(value).toFixed(2);
}
});
You can try this :
That is a clean way to render formated data in view using angularjs as MVC
frontend framework :
Create a filter in your angular application.
Include your filter in your index.html.
use your filter like this : {{somedata | filterName}}
That is a simple angular filter to solve your problem, hope it will help you :
angular.module('app')
.filter('formatHeader', function() {
return function(data) {
if(angular.isNumber(data)) {
return data.toFixed(2);
}
return data;
}
});
And us it like this :
<table>
<tr>
<th ng-repeat='header in headers'>{{header.th}}</th>
</tr>
<tr>
<td ng-repeat='data in headers'>
<div ng-repeat='inner in data.td'>
<span ng-repeat='(prop, val) in inner'>{{val | formatHeader}}</span>
</div>
</td>
</tr>
You can take a look about these references :
angular functions
filter doc.
angular tutorials

Where should I write general purpose controller function in angular.js?

I am writing some functions for check/uncheck all for table list and it is working fine,
Controller is,
invoiceApp.controller('itemController', ['$scope', 'itemService', '$route', function ($scope, itemService, $route) {
$scope.checkAllItem;
$scope.listItem = {
selected: []
};
$scope.checkUncheck = function () {
if ($scope.checkAllItem) {
$scope.listItem.selected = $scope.items.map(function (item) {
return item.id;
});
} else {
$scope.listItem.selected = [];
}
};
HTML TABLE,
<table id="dt_basic" class="table table-bordered table-hover" width="100%">
<thead>
<tr>
<th class="text-center" width="5%">
<input type="checkbox" name="checkbox-inline" ng-model="checkAllItem" ng-click="checkUncheck()">
<input type="checkbox" name="checkbox-inline" ng-click="uncheckAll()">
</th>
<th width="15%" ng-click="sort()">Name<i class="fa fa-sort small"></i></th>
<th width="65%">Description</th>
<th width="5%">Unit</th>
<th width="10%">Rate</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items" data-toggle="modal" data-target="#itemModel" ng-click="getItem(item.id)" style="cursor: pointer">
<td class="text-center">
<input type="checkbox" checklist-model="listItem.selected" checklist-value="item.id">
</td>
<td><a>{{item.name}}</a></td>
<td>{{item.description}}</td>
<td>{{item.unit}}</td>
<td>{{item.rate}}</td>
</tr>
</tbody>
</table>
It is working fine,Here my problem is,In my project I have many tables in different pages,I have to copy past this same code (Talking about Controller only ) to everywhere.Is there any method to write it generally?
I tried with $routescope,
but It is not working with ng-model,Is there any method to implement the same?
You could turn it into a service then inject the service to whichever controller needs it. You can now also include other commonly used functions used to manipulate data in those. See,
http://jsbin.com/madapaqoso/1/edit
app.factory("toolService", function(){
return {
checkUncheck: function(listItem) {
listItem.selected = [];
}
}
});
I didn't add the added complexity of your function, but you get the idea.
Alternatively, use a directive. I show it in the jsbin as well. Though, I'd prefer a service since services are made for managing data and directives are more concerned with DOM editing and binding $watchers/events etc. Or perhaps you could persist the data with a service, then use a custom directive to handle all the clicks on the table.
I have written a custom directive
invoiceApp.directive('checkUncheck', function () {
return {
restrict: 'E',
replace: true,
template: '<input type="checkbox" name="checkbox-inline" ng-model="checkAllItem" ng-click="checkUncheck()">',
link: function (scope) {
//check/uncheck and delete
scope.checkAllItem;
scope.listItem = {
selected: []
};
scope.checkUncheck = function () {
if (scope.checkAllItem) {
scope.listItem.selected = scope.items.map(function (item) {
return item.id;
});
} else {
scope.listItem.selected = [];
}
};
}
};
});
In HTML,
<check-uncheck></check-uncheck>
Now I can share checkUncheck function with most of table view in my project.

Simple $scope.$watch not called?

I have a simple table app which gets JSON data from a database. It passes the data via parameter to my app controller, which then filters the data. This works great. However, it is a lot of data (hundred thousand objects). I have search boxes that I use to try and filter the data, and when the search watch should be getting called (when someone types something in the search box), it doesn't. Am I missing something?
js:
var app = angular.module('SortingTables', ['ui.bootstrap']);
//Dependencies which are services, providers or factories must map to string types, which are then passed into the instance function
app.filter('startFrom', function () {
return function (input, start) {
start = +start; //parse to int
return input.slice(start);
};
});
app.controller('Ctrl', function ($scope, filterFilter, dataTable) {
$scope.currentPage = 1;
$scope.itemsPerPage = 25;
$scope.totalItems = 0;
$scope.predicate = '';
$scope.searchBuffer = {
$: ''
};
$scope.filtered;
//This function has sort of been abstracted...
//The purpose of this function is to delay the update so the user gets a chance to finish typing before the filter is applied.
//Newer versions of angularjs have the ng-model-options: debounce=100 but we can't use that since we have IE 8 on dev boxes
$scope.$watch('searchBuffer', function (term) {
console.log('The watch on searchBuffer was called');
$scope.filtered = filterFilter(dataTable, term);
$scope.totalItems = $scope.filtered.length;
});
$scope.pageChanged = function () {
$scope.currentRow = $scope.currentPage * $scope.itemsPerPage - $scope.itemsPerPage;
};
});
html
<div ng-app="Components" ng-controller="Ctrl">
<hr/>
<table class="table table-striped">
<tr>
<th>Technical Owner
<br />
<input type="search" ng-model="searchBuffer['Technical Owner']">
</a>
</th>
<th>Branch
<br />
<input type="search" style="width: 40px" ng-model="searchBuffer.Branch">
</a>
</th>
<th>Sub Pillar
<br />
<input type="search" ng-model="searchBuffer['Sub Pillar']">
</a>
</th>
<th>Path
<br />
<input type="search" ng-model="searchBuffer.Path">
</a>
</th>
<th>Name
<br />
<input type="search" ng-model="searchBuffer.Name">
</a>
</th>
<th>Description
<br />
<input type="search" ng-model="searchBuffer.Description">
</a>
</th>
</tr>
<tr ng-repeat="ComponetOwner in filtered | startFrom:currentPage | orderBy:predicate:reverse | limitTo:itemsPerPage">
<td>{{ComponetOwner["Technical Owner"]}}</td>
<td>{{ComponetOwner.Branch}}</td>
<td>{{ComponetOwner["Sub Pillar"]}}</td>
<td>{{ComponetOwner.Path}}</td>
<td>{{ComponetOwner.Name}}</td>
<td>{{ComponetOwner.Description}}</td>
</tr>
</table>
<pagination items-per-page="itemsPerPage" total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()"></pagination>
</div>
When I type something in the search box, $watch doesn't get called. What's going on?
searchBuffer is an object. The third optional argument of $watch needs to be set to 'true' for watching objects/arrays (that is for deep watching).
Read this:
$watch an object
You can do $watchCollection which will watch all the objects within an object.
Not as deep as setting the third optional argument which is true for yout $watch function.
Here is a good blog about it: http://www.bennadel.com/blog/2566-scope-watch-vs-watchcollection-in-angularjs.htm

Categories

Resources