Empty table rows with ng-repeat, AngularJS - javascript

I have input fields that you can submit, and the data that you entered is inserted into an database. This data is then looped out in a table with ng-repeat:
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Sträcka</th>
<th>Tid</th>
<th>Jämför</th>
</tr>
</thead>
<tr ng-repeat="info in test"><td>{{info.stracka}}</td><td>{{info.tid}}</td><td><input type="checkbox" id="{{info.id}}" class="checkboxfisk" ng-click="testa(info.id)"></tr>
</table>
The problem is that, When the database table is empty, and you are submiting data for the first time, 3 empty TR's rows are printed out, after you have hit submit. I used firebug to debug this, and the HTML look like this when I hover on the empty TR-rows:
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Sträcka</th>
<th>Tid</th>
<th>Jämför</th>
</tr>
</thead>
<tbody>
<tr class="ng-scope" ng-repeat="info in test">
<td class="ng-binding"></td>
<td class="ng-binding"></td>
<td>
<input id="" class="checkboxfisk" type="checkbox" ng-click="testa(info.id)">
</td>
</tr>
<tr class="ng-scope" ng-repeat="info in test">
<td class="ng-binding"></td>
<td class="ng-binding"></td>
<td>
</tr>
<tr class="ng-scope" ng-repeat="info in test">
<td class="ng-binding"></td>
<td class="ng-binding"></td>
<td>
</tr>
</tbody>
</table>
<form class="ng-pristine ng-invalid ng-invalid-required" novalidate="" ng-submit="submitForm(userForm.$valid)" name="userForm">
As you can see, there are td's with classname of ng-binding. What is this? Can anyone help me?
Here is my controller:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data.data;
});
$scope.form = {};
$scope.checkboxes = [];
$scope.testa = function(id) {
$scope.checkboxes.push(id);
};
$scope.submitForm = function(isValid) {
if(isValid)
{
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
console.log($scope.form);
}).error(function(data, status) {
});
}
};
});
EDIT: The problem was in my backend. I've have forgotten to add a parameter that is returned after that the mysql query is executed.

I see two possibilities.
In first, you should initialize your test scope variable before the $http call (to ensure it is initialized even if http request fails). And then create a method updateTest which will be called on succes of the submit form (to update test variable).
Your code should be like that:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
// METHOD to update test items
updateTest = function() {
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data.data;
});
};
// init variables
$scope.form = {};
$scope.checkboxes = [];
$scope.test = [];
$scope.testa = function(id) {
$scope.checkboxes.push(id);
};
$scope.submitForm = function(isValid) {
if(isValid)
{
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
console.log($scope.form);
// update test item (to get back newly created one)
updateTest();
}).error(function(data, status) {
});
}
};
// first test items update
updateTest();
});

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;
});

AngularJS - Nested ng-repeat using two objects

Controller:
$scope.init = function(team){
$http.get("/getLeaderByTeamID/"+team.id)
.success(function (data, status, headers, config) {
// this is the object that I need to list in the table
$scope.leader = data;
})
.error(function (data, status, header, config) {
$log.error("Error!");
});
}
The data-ng-repeat directives in the table:
<table>
<thead>
<tr>
<th>Team</th>
<th>Leader</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="team in teams" data-ng-init="init(team)">
<td>{{team.name}}</td>
<td data-ng-repeat="l in leader">{{l.name}}</td>
</tr>
</tbody>
The logic is as follow:
When every team is listed the init() function will send the object to the controller.
In the other side the init() function will make a query with the ID team in order to get its respective leader.
The function will return one object and the second ng-repeat directive will list this into its respective team object.
But as I showed the list is wrong because one same object is listed in every team.
I was thinking create an array into the init() function with every object but I don't know how to concatenate every object in order to create an array.
Any suggestions?
I think you'r just updating $scope.leader value in every request ,so at the end $scope.leader will have the same value for all teams. try this.
$scope.init = function(teamId){
$http.get("/getLeaderByTeamID/"+teamId)
.success(function (data, status, headers, config) {
// this is the object that I need to list in the table
$scope.leader[teamId] = data;
})
.error(function (data, status, header, config) {
$log.error("Error!");
});
<table>
<thead>
<tr>
<th>Team</th>
<th>Leader</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="team in teams" data-ng-init="init(team.id)">
<td>{{team.name}}</td>
<td data-ng-repeat="l in leader[team.id]">{{l.name}}</td>
</tr>
</tbody>
or you can use function return leaders array in the second ng-repeat like:
<td data-ng-repeat="l in getLeader(team.id)">{{l.name}}</td>

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.

Ajax, json in AngularJS

I am trying to use the $http.get API to get a json data and then use it in my HTML tags.
I seem to miss something in the concept. here is my javascript:
var CouponsApp = angular.module('CouponsController', []);
CouponsApp.controller("CellCouponController", function($scope, $http){
$http.get('CouponsJSON.json').
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
Here is my HTML:
<div id="CellTable" ng-controller="CouponController">
<p> Cell Phones Coupons</p>
<table border=1>
<tr>
<th>Model</th>
<th>Manufacturer</th>
<th>Cell Image</th>
<th>Manufacturer Url</th>
<th>Local Vendor</th>
<th>Local Vendor Address</th>
</tr>
<tr ng-repeat="coupon in coupons">
<td>{{CellPhones.model}}</td>
<td>{{CellPhones.manufacturer}}</td>
<td>
<img src="{{CellPhones.CellImage}}" alt="{{CellPhones.CellPhones}}" width="50px;" height="50px;" width="60px">
</td>
<td>
{{CellPhones.manufacturer}} URL
</td>
<td>{{CellPhones.localVendor}}</td>
<td>{{CellPhones.localVendorAddress}}</td>
</tr>
</table>
</div>
What is the correct way to get the json data, insert it to an object and then parse it in the ng-repeat?
You must define a $scope.coupons = {}; in your controller , and then attach your get data to that like this :
controller:
$scope.coupons = {};
$http.get('CouponsJSON.json')
.success(function(data){
// first console.log(data) it to check getting data is correctly working :
console.log(data);
$scope.coupons.coupon = data;
// its good practice to always use a DOT!!
})
Now in your html you can use ng-repeat like this :
<div ng-repeat="coup in coupons.coupon">
{{coup}}
</div>

How to use URL parameters in a GET request with Angular?

I have very simple application that has two features. One, it lists all of the keys two, it is supposed to display one particular key (and the associated value).
Here is the first part that list the keys:
var app = angular.module('flipDaSwitch', ['ngRoute']);
app.controller('ListKeys', function($scope, $http) {
$scope.getKeys = function() {
$http.get('/api/keys').
success(function (data) {
$scope.buckets = data;
}).
error(function (data){
$scope.buckets = {}
});
};
});
I am wondering how could I get a particular key from the API. The current HTML:
<div name="listkeys" class="container">
<div class="starter-template">
<div ng-bind-html="message"></div>
<table class="table table-striped table-bordered table-condensed sortable" ng-init="getKeys()">
<tr>
<th>Bucket:</th>
</tr>
<tr ng-repeat="bucket in buckets">
<td>
<a ng-href="/show_key.html#/key/{{bucket}}">{{bucket}}</a>
</td>
</tr>
</table>
</div>
</div>
Obviously the show_key.html gets the key in the URL like this:
/show_key.html#/key/efd1ae55a5-random_string
I am not sure how could I issue a get request based on the URL parameters.
Inject $routeParams in controller:
app.controller('ListKeys', function($scope, $http, $routeParams) {
...
Docs
Also there is a bunch of questions about this.

Categories

Resources