Angularjs ng-repeat doesn't work as expected - angularjs

I have an Angularjs controller(Angularjs 1.5.6) which calls a function from a python script, which returns an array of elements. I am trying to do an ng-repeat so that they appear in the table but for some reason, it doesn't show the elements of the array.
The 'Go' button in the html template triggers the function getSID which makes an HTTP call to a python script that returns an array. At the same time, the function also sets the scope, showval to true such that the table in the html appears only after the button is clicked.
<script>
angular.module('navigator', [])
.controller('HomeCtrl', function($scope, $http) {
$scope.getSid = function (sid) {
console.log(sid);
$http({
method: 'POST',
url: '/getMachine',
data: {sid:$scope.sid}
}).then(function(response) {
$scope.machines = [];
var object1 = response.data;
$scope.machines.push(object1);
//console.log(object1);
console.log($scope.machines);
$scope.showval = true;
}, function(error) {
console.log("hello");
console.log(error);
});
};
})
HTML code:
<div class="input-group mb-3 input-group-lg">
<div class="input-group-prepend">
<span class="input-group-text">Enter the SID</span>
</div>
<input type="text" class="form-control" ng-model="sid">
<button type="button" class="btn btn-outline-secondary" ng-click="getSid(sid)" ng-model="show" >
GO!
</button>
</div>
<div ng-show="showval">
<table class="table table-dark" >
<thead>
<tr>
<th scope="col">SID</th>
<th scope="col">Cluster</th>
<th scope="col">Node</th>
<th scope="col">Physical ip</th>
<th scope="col">Logical ip</th>
<th scope="col">Logical Host</th>
<th scope="col">Physical Host</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in machines">
<td>{{item}}</td>
</tr>
</tbody>
</table>
</div>
I googled ng-repeat and so several examples in plunker and I am following the same code but my code doesn't seem to work. Would be grateful for any assistance. Thanks for your time.

Your need to enclose track by $index within quotes as well,
<tr ng-repeat="item in machines track by $index">

Guilty of not posting the complete details. I was working with python flask and realized that the conflict is due to Jinja2.
I had to use the {%raw} {%end raw} so that Jinja2 processes it as an html.
More details in this Link
Now my code looks like this and ng-repeat is working.
{% raw %}
<tbody>
<tr ng-repeat="item in machines" >
<td>{{item}}</td>
</tr>
</tbody>
{% endraw %}

Related

dirPagination numbers not change when ng-model search put something

At first, I'm using dirPagination. The problem is that when I search something, it's filtered correctly, but pagination number not change and also show all last number in pagination without any change and I see some page is empty because it does filter but page number is show.
<div data-ng-controller='productsController'>
<form `class='form-inline'>
<div class='form-group'>
<label>search</label>
<input type='text' data-ng-model='search' class='form-control' placeholder='search' />
</div>
</form>
<table class='table table-striped'>
<thead>
<tr>
<th>#</th>
<th>product</th>
<th>imet</th>
</tr>
</thead>
<tbody>
<tr dir-paginate='product in products|itemsPerPage:12|filter:search|orderBy:sortKey:reverse'>
<td>{{product.id}}</td>
<td>{{product.productName}}</td>
<td>{{product.time}}</td>
</tr>
</tbody>
</table>
<dir-pagination-controls max-size='10' direction-links='true' boundary-links='true' >
</dir-pagination-controls>
<script>
(function(){
var app = angular.module('products', ['angularUtils.directives.dirPagination']);
app.controller('productsController', function($scope, $http){
$scope.products = [];
$http.get('/products/json').success(function(data){
$scope.products= data;
});
});
})();
</script>
</div>
itemsPerPage must be the last filter, as below:
<tr dir-paginate='product in products | filter: search | orderBy: sortKey: reverse | itemsPerPage: 12'>
For more explanation, check it on FAQ on michaelbromley/angularUtils/.

nested ng-repeat with 2 json data sources

This is going to be complicated to explain, so please bear with me.
The task: To repeat json data in a table. (list of products, last cell is a button).
The problem: On clicking the button, another repeated list of rows appears under the product (second data-repeat, accessories of the products) but must match the product.
Now i can get the first part. I can even ng-repeat the second part, and the ng-click. However, every button repeats the same thing. I know that $index probably can be used here, i just dont understand how.
So how do i get the accessories for each individual product, to only show when the product button is clicked?
Example: Product 1 has 5 accessories. Product 2 has 1 accessory. If i click the product 1's button, 5 accessories show underneath it. If i click the product 2's button, 1 accessory shows below it.
Code:
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12" style="padding:0px;">
<table class="table table-bordered" ng-controller="tableCtrl_1" ng-switch="test">
<tr style="height:70px;background-color:#0C4791;">
<th style="text-align:center;color:white;vertical-align:middle;">Flexi Floor/Low Wall</th>
<th style="text-align:center;color:white;vertical-align:middle;">Cooling</th>
<th style="text-align:center;color:white;vertical-align:middle;">Heating</th>
<th style="text-align:center;color:white;vertical-align:middle;">Nominal Capacities(cooling/heating)</th>
<th style="text-align:center;color:white;vertical-align:middle;">Pipe Length</th>
<th style="text-align:center;color:white;vertical-align:middle;">List Price</th>
<th style="text-align:center;color:white;vertical-align:middle;">Quantity</th>
</tr>
<tr ng-repeat-start = "getdata in getdata | filter:'Flexi Floor/Low Wall':true">
<td style="vertical-align:middle;text-align:center;">{{getdata.model_no_from}} + {{getdata.model_no_to}}</td>
<td style="vertical-align:middle;text-align:center;">{{getdata.cooling}}</td>
<td style="vertical-align:middle;text-align:center;">{{getdata.heating}}</td>
<td style="vertical-align:middle;text-align:center;"><span style="color:blue">{{getdata.nominal_cooling}}</span><span style="color:red;">{{getdata.nominal_heating}}</span></td>
<td style="vertical-align:middle;text-align:center;">{{getdata.pipe_length}}</td>
<td style="vertical-align:middle;text-align:center;"><span style="font-weight:bold;">{{getdata.system_listPrice | currency: "£"}}</span></td>
<td style="vertical-align:middle;text-align:center;"><button class="btn btn-default btn-large btn-block" ng-click="showDetails = ! showDetails">Select</button></td>
</tr>
<tr ng-repeat-end ng-class="{ 'hidden': ! showDetails }" >
<!--<td style="vertical-align:middle;text-align:center;">{{getdata_2.sales_description}}</td>
<td style="vertical-align:middle;text-align:center;">{{getdata_2.list_price}}</td> -->
<td colspan="7" style="text-align:center;vertical-align:middle;">test 1</td>
</tr>
</table>
</div>
</div>
</div>
</body>
And the controller:
testApp.controller('tableCtrl_1', function($scope, $http, ajaxServices, secondaryServices){
getdata();
function getdata(){
$http.post("angular_data.php").success(function(data){
$scope.getdata = data;
});
};
ajaxServices.getProducts().success(function(data){
$scope.getdata = data
});
secondaryServices.getProducts_2().success(function(data){
$scope.getdata_2 = data
});
});
Services:
testApp.factory('ajaxServices', function($http){
return {
getProducts: function(){
return $http.get('angular_data.php', {data: {}})
}
}
});
testApp.factory('secondaryServices', function($http){
return {
getProducts_2: function(){
return $http.get('angular_data_2.php', {data: {}})
}
}
});
Pardon the inline-styling, just easier for me while testing.

Getting key value pairs from json reponse into angular js

How do I map the json response to the table in html page.
Angularjs Controller:
app.controller('tableController', function ($scope,$http)
{
$scope.customerTable = [];
$scope.getTable = function ()
{
$http.get('<%=request.getContextPath()%>/GetTable.do').success(function (data)
{
$scope.customerTable = data;
// console.log($scope.customerTable);
});
};
});
html code:
<div ng-controller="tableController">
<!--<p>Click <a ng-click="getTable()">here</a> to load data.</p>-->
<table>
<tr>
<th>Card Number</th>
<th>First Name</th>
<th>Opening Balance</th>
<th>Withdrawal</th>
<th>Deposit</th>
<th>Closing Balance</th>
<th>Tx Date</th>
<th>Usage_Type</th>
</tr>
<tr ng-repeat="data in customerTable ">
<td>{{data[0]}}</td>
</tr>
</table>
<br>
<button class="form-control btn btn-success" type="submit" ng-click="getTable()">Load Table Data</button>
</div>
The response is in one array with key, value pairs. Do I have to modify the ng-repeat?
Here is the json response:
[{"TXDATE":"1-Aug-14","FIRST_NAME":"MOSES","USAGE_TYPE":"HOTELS/MOTELS/RESORTS","WITHDRAWAL":"15200","DEPOSIT":"0","CARD_NUMBER":"AL98****66325","CLOSING_BAL":"-362764.96","OPENING_BALANCE":"0"}]
You can use the fields in every object:
<tr ng-repeat="data in customerTable ">
<th>{{data.FIRST_NAME}}</th>
<th>{{data.CARD_NUMBER}}</th>
...
</tr>
Perhaps you could use a directive for this kind of table related iterations.
Use the attributes. it should be:
<tr ng-repeat="data in customerTable ">
<td>{{data.TXDATE}}</td> <!-- result: 1-Aug-14 -->
</tr>
and so on.
Yes, you have to modify it.
<tr ng-repeat="data in customerTable ">
<td>{{data['CARD_NUMBER']}}</td>
<td>{{data['TXDATE']}}</td>
<td>{{data['OPENING_BALANCE']}}</td>
...
</tr>

ng-show does not work with custom directive

I've just started using AngularJS and wanted to create a custom template directive for creating "in-place" editable tables. The idea would be to have something like:
<tr ng-repeat="customer in model.customers">
<ng-template ng-hide="customer === model.selectedCustomer"> <!-- display template-->
<td>{{customer.name}}</td>
</ng-template>
<ng-template ng-show="customer === model.selectedCustomer"> <!-- edit template -->
<td><input type="text" ng-model="customer.name"/></td>
</ng-template>
</tr>
It could then also be extended to specify a templateUrl e.g. <ng-template template-url="foo.html"></ng-template>
When I apply the ng-show directive to my custom directive it does not work. Here's the code for my directive:
var demo = angular.module("demo", [])
.directive("ng-template", function() {
return {
restrict: "E",
replace: true,
transclude: true
}
});
and HTML (http://jsfiddle.net/benfosterdev/ASXyy/):
<div ng-app="demo">
<table>
<tr ng-repeat="name in ['jane', 'john', 'frank']">
<ng-template ng-show="name !== 'frank'">
<td>{{name}}</td>
</ng-template>
</tr>
</table>
</div>
Furthermore, when I look at the generated HTML my custom directive doesn't even appear in the table:
<div ng-app="demo" class="ng-scope">
<ng-template ng-show="name !== 'frank'" class="">
</ng-template>
<table>
<tbody>
...
</tbody>
</table>
</div>
Essentially I'm trying to avoid writing code like this (setting the ng-show directive on every <td> element):
<table>
<tr ng-repeat="customer in customers">
<ng-template>
<td ng-hide="isSelected">{{customer.name}}</td>
<td ng-hide="isSelected">{{customer.age}}</td>
<td ng-hide="isSelected"><button ng-click="edit(customer)"</td>
<td ng-show="isSelected"><input type="text" ng-model="customer.name"/></td>
<td ng-show="isSelected"><input type="text" ng-model="customer.age"/></td>
<td ng-show="isSelected"><button ng-click="save(customer)"</td>
</ng-template>
</tr>
</table>
A couple of things occur to me when I look at your code.
ng-include offers very similar functionality to your proposal for extending ng-template. If you're going to load a view based on the state of the underlying model then I think this would be the way to go.
If you're not going to be loading the template from a separate view file, why not just use ng-show (or ng-if / ng-switch, which I prefer in most cases) on your td element?
Here is some example code using ng-include:
<table>
<thead>
<th>One</th>
<th>Two</th>
<th>Three</th>
<th></th>
</thead>
<tbody>
<tr ng-repeat="item in items" ng-include="getTemplate(item)"></tr>
</tbody>
</table>
Here is the full JSFiddle: http://jsfiddle.net/qQR6j/2.
Use ng-repeat-start and ng-repeat-end to specify the two alternative <tr> tags.
<div ng-app="demo">
<table ng-controller="Ctrl">
<tr ng-repeat-start="name in ['jane', 'john', 'frank']" ng-hide="isSelected(name)">
<td>{{name}} <button ng-click="select(name)">edit</button></td>
</tr>
<tr ng-repeat-end ng-show="isSelected(name)">
<td>{{name}}!</td>
</tr>
</table>
</div>
With this javascript
var demo = angular.module("demo", []);
demo.controller("Ctrl",
function Ctrl($scope) {
var selected;
$scope.isSelected = function(name) {
return selected === name;
};
$scope.select = function(name) {
selected = name;
};
});
Live example: http://jsfiddle.net/6FtjG/1/
Your browser renders the 'ng-template' outside of the table because its not a valid child of tr. Even if you have set replace to true, the directive needs to be rendered before it can be replaced.
You can see it is because of the table, because this does work:
<div>
<div ng-repeat="name in ['jane', 'john', 'frank']">
<ng-template ng-show="name !== 'frank'">
<div >{{name}}</div>
</ng-template>
</div>
</div>
see: Fiddle
This is something your browser does so you cannot avoid it.

Why would ng-repeat fail to loop with $http.get JSON but work when it's hard coded?

I have an Angular project using ng-repeat that has been working fine with a temp JSON string coded into the controller:
function DocsController($scope, $http){
$scope.applicationData = [
{"Item":"1", Value: "Red"}, {"Item":"2", Value: "Orange}
];
}
But for some reason, when I move that JSON into a file, and pull it in via $http.GET, the ng-repeat stops working. No loops, nothing- even though I can get applicationData.length and other properties off the object outside the loop:
$http.get('jsonData/docs.json').success(function(data) {
alert (data);
$scope.applicationData = data;
});
In the above example, the alert shows the JSON string, so I know it's getting loaded properly. I can call {{applicationData.length}} and it will render 2. So I know the data is there, it's just the ng-repeat stops looping when the data is acquired via $http.get.
Any ideas? Many thanks!
Item template (Note that the line {{applicationData.length}} renders properly- so I know the data is there).
<div class="row-fluid">
<div class="box span12" ng-controller="DocsController">
<div class="box-header">
<h2><i class="halflings-icon list-alt"></i><span class="break"></span><strong>Application Documents</strong></h2>
<div class="box-icon">
<span><input type="checkbox" id="completedApplicationCheckbox" ng-model="trueApplication" value="option1" checked>Show Completed </span>
<i class="halflings-icon chevron-up"></i>
</div>
</div>
</br>
<table class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr>
<th>Document Title <i class="halflings-icon chevron-down"></i></th>
<th>Date <i class="halflings-icon chevron-down"></i></th>
<th>Owner <i class="halflings-icon chevron-down"></i></th>
<th>Status <i class="halflings-icon chevron-down"></i></th>
<th>Actions <i class="halflings-icon chevron-down"></i></th>
</tr>
</thead>
<tbody>
<h2>{{applicationData.length}}</h2>
<tr ng-repeat="item in applicationData" class="application-{{item.status}}">
<td><i class="halflings-icon file"></i> {{item.name}}</td>
<td class="center">{{item.lastModified | date:'short'}}</td>
<td><i class="halflings-icon {{getIconType(item.owner)}}"></i> {{item.owner}}</td>
<td class="center" ng-bind-html-unsafe="createStatus(item.status)">
</td>
<td class="center" ng-bind-html-unsafe="createActionButton(item.status)">
</td>
</tr>
</tbody>
</table>
</div>
</div>
-Edit-
try using .then()
$http.get('jsonData/docs.json').then(function(data){
$scope.applicationData = data
});
Try this:
$scope.applicationData = [];
$http.get('jsonData/docs.json').success(function(data) {
$scope.applicationData.push(data);
});
I realized there was a conflict with the datatable jquery plug-in (http://www.datatables.net/). I'm afraid it won't work with Angular, because it's an excellent piece of software, but I'm having to disable it for now.

Resources