Ajax, json in AngularJS - javascript

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>

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>

Angularjs Smart table not working for Dynamic data

I have a situation where i am using angularJs smart table for filtering.
html:
<section class="main" ng-init="listAllWorkOrderData()">
<table st-table="listWorkOrderResponse">
<thead>
<tr>
<th st-sort="id">ID <i></i></th>
<th st-sort="project">Project <i></i></th>
</tr>
</thead>
<tbody ng-repeat="workOrder in listWorkOrderResponse">
<tr>
<td>{{workOrder.id}}</td>
<td>{{workOrder.project}}</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
</section>
I am testing for 2 different cases.
In my controller first i call the same function but send dummy array and in the second case i send the array received from the api call.
1. Dummy data
$scope.listAllWorkOrderData = function () {
var listWorkOrderResponse = [{"id":"1","project":"project1"},{"id":2,"project":"project2"},{"id":"3","project":"project3"}];
}
2. I am using a service and fetching data through api.
$scope.listAllWorkOrderData = function () {
TestService.listAllWorkOrderData().then(function (response, status, headers, config) {
if (response != undefined && response != null) {
if (!$scope.listWorkOrderResponse) {
$scope.listWorkOrderResponse = [];
}
$scope.listWorkOrderResponse = response;
}, function (response, status, headers, config) {
console.log(response);
});
When i am using case1 the sorting works fine.
But when i use case2 the sorting does not work. Onclick of it the data just disappears.
I tried debugging to see whether the listAllWorkOrderData function is being called again when we click on the filter.But it is just called once when the page is loaded to populate the table.So that means the data is present in the listWorkOrderResponse. Then why is it not sorting?
I checked the response for both the situation by printing them the only difference i found was that the listWorkOrderResponse which comes from the api call has a $$hashKey: "object:363" added to it.
Can anyone point me what mistake i am doing.
I was able to resolve this issue by using stSafeSrc attribute
In the controller we add
$scope.listAllWorkOrderData = function () {
TestService.listAllWorkOrderData().then(function (response, status, headers, config) {
if (response != undefined && response != null) {
if (!$scope.listWorkOrderResponse) {
$scope.listWorkOrderResponse = [];
}
$scope.listWorkOrderResponse = response;
// we add one more list.
$scope.displayedWOList = [].concat($scope.listWorkOrderResponse);
}, function (response, status, headers, config) {
console.log(response);
});
and then in the html table we add the stSafeSrc attribute.
stSafeSrc attribute from the Smart Table document
http://lorenzofox3.github.io/smart-table-website/
stSafeSrc attribute
If you are bringing in data asynchronously (from a
remote database, restful endpoint, ajax call, etc) you must use the
stSafeSrc attribute. You must use a seperate collection for both the
base and safe collections or you may end up with an infinite loop.
<section class="main" ng-init="listAllWorkOrderData()">
<table st-table="displayedWOList" st-safe-src="listWorkOrderResponse">
<thead>
<tr>
<th st-sort="id">ID <i></i></th>
<th st-sort="project">Project <i></i></th>
</tr>
</thead>
<tbody ng-repeat="workOrder in displayedWOList">
<tr>
<td>{{workOrder.id}}</td>
<td>{{workOrder.project}}</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
</section>
Why it is not working i don't know but yo can solve it by doing like below
repeat your response & create a new object & push it into an array..
var res = [];
for(var i=0; i<response.length; i++) {
var x = {"id":response[i].id, "project":response[i].project};
arr[i] = angular.copy(x);
}

Empty table rows with ng-repeat, AngularJS

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

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