Mapping existing data in AngularJS - javascript

I'm starting to learn some AngularJS and am trying to determine its practicality when working along side ASP.NET MVC.
Let's say I have a view which displays beers from a repository in a table. I could output the information in two ways.
1.Using MVC's Razor Engine
Here, the model containing the beers is processed on the server and the html page rendered.
<h3>Rendered using Razor!</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Colour</th>
<th>Tasted?</th>
</tr>
</thead>
<tbody>
#foreach (var beer in Model)
{
<tr>
<td>#beer.Name</td>
<td>#beer.Colour</td>
<td>#beer.Tried</td>
</tr>
}
</tbody>
</table>
2.Using Angular repeat
Here, the HTML is returned straight away and angular performs a AJAX call to the controller to retrieve its model. After it has that data it outputs it into the table.
<h3>Rendered using Angular!</h3>
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Name</th>
<th>Colour</th>
<th>Tasted?</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="beer in model">
<td>{{ beer.Name }}</td>
<td>{{ beer.Colour }}</td>
<td>{{ beer.Tried }}</td>
</tr>
</tbody>
</table>
Controller
angular.module('BeerController', [])
.controller('BeerCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.model = {};
$http.get('/Beer/GetBeers').success(function (data) {
$scope.model = data;
});
}]);
My Question
Is there a way to use the Razor engine for the initial load of the data and Angular for everything else (paging calls, searching etc.)? In other words, how do I bind existing html to a controllers model in AngularJS?
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Colour</th>
<th>Tasted?</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fosters</td>
<td>Gold</td>
<td>True</td>
</tr>
<tr>
<td>Becks</td>
<td>Amber</td>
<td>False</td>
</tr>
<tr>
<td>Cobra</td>
<td>Gold</td>
<td>True</td>
</tr>
</tbody>
</table>

In your MVC Controller
public ActionResult Index()
{
var model =.....
//optional
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
ViewBag.data = JsonConvert.SerializeObject(model, Formatting.Indented, jsonSerializerSettings);
return View()
}
In your view Index.cshtml
...
#section Scripts {
//make sure that all anular scripts are loaded before that
<script>
angular.module('BeerController').service('dataService', function () {
var data= #Html.Raw(ViewBag.data);
return {
data:data
}
});
...
</script>
}
Angular Part:
angular.module('BeerController', [])
.controller('BeerCtrl', ['$scope', '$http','dataService', function ($scope, $http,dataService) {
// now you can get data from your dataService without extra trip to your server
$scope.model = dataService.data
....
}]);

Related

How to use *ngIf condition inside the <td> field of table using angular where *ngFor is looping?

Actually in my component.ts file i have used the api to call the method and it is returning me array of objects.
And my problems began as I m trying to use ngIf in tag to hide/show column according to the client.auditorGroup as it is either true or false(it is of type boolean) but it is not giving me access:
1st code:
ngOnInit() {
this.http.get('http://localhost:8080/api/selections')
.subscribe((data: any[]) => {
this.clients = data;
console.log(this.clients);
this.chRef.detectChanges();
const table: any = $('table');
this.dataTable = table.DataTable();
});
}
And in my html code I have used this Edit Delete and it is h
<table class="table table-bodered">
<thead>
<tr>
<th>Mag No</th>
<th>SelectionDate</th>
<th> SelectedBy</th>
<th>PanEximNumber</th>
<th>Name</th>
<th>Address</th>
<th>PhoneNumber</th>
<th>SelectionType</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let client of clients">
<td>{{client.selectionId}}</td>
<td>{{client.selectionDate}}</td>
<td>{{client.selectedBy}}</td>
<td>{{client.panEximNumber}}</td>
<td>{{client.name}}</td>
<td>{{client.address}}</td>
<td>{{client.phoneNumber}}</td>
<td>{{client.selectionType}}</td>
<td *ngIf="{{client.auditorGroup}}==false">Edit Delete</td>
</tr>
</tbody>
</table>
Remove the interpolation {{}} when using *ngIf
<td *ngIf="!client.auditorGroup">Edit Delete</td>

Access each individual custom cell with Angular bootstrap calendar

I'm working on an app where I need a calendar skeleton (without the standard events) so I can put tables inside each cell, so I'm using the Angular Bootstrap Calendar with custom cell templates. I have everything working fine in terms of displaying the custom template in each cell and being able to navigate between months, but I need to be able to access each individual day and make data available in each one.
Here's my controller:
(function() {
angular.module('myApp')
.controller('calendarController', function($scope, $state, moment, calendarConfig) {
var vm = this;
calendarConfig.templates.calendarMonthCell = 'views/calendar/dayTemplate.html';
calendarConfig.dateFormatter = 'moment';
vm.events = [];
vm.calendarView = 'month';
vm.viewDate = moment().startOf('month').toDate();
$scope.$on('$destroy', function() {
calendarConfig.templates.calendarMonthCell = 'mwl/calendarMonthCell.html';
});
});
})();
and the corresponding dayTemplate.html:
<div class="cal-month-day">
<span
class="pull-right"
data-cal-date
ng-click="calendarCtrl.dateClicked(day.date)"
ng-bind="day.label">
</span>
<!--
<small style="position: absolute; bottom: 10px; left: 5px">
There are {{ day.events.length }} events on this day
</small> -->
<!-- <table class="table table-bordered table-condensed"> -->
<table class="table table-bordered table-condensed">
<thead>
<tr>
<td>Station</td>
<td>Position</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="3" align="top">1</td>
<td>Position</td>
<td>Name</td>
</tr>
<tr>
<td>Position</td>
<td>Name</td>
</tr>
<tr>
<td>Position</td>
<td>Name</td>
</tr>
</tbody>
</table>
<table class="table table-bordered table-condensed">
<tbody>
<tr>
<td rowspan="3" align="top">2</td>
<td>Position</td>
<td>Name</td>
</tr>
<tr>
<td>Position</td>
<td>Name</td>
</tr>
<tr>
<td>Position</td>
<td>Name</td>
</tr>
</tbody>
</table>
<table class="table table-bordered table-condensed">
<tbody>
<tr>
<td rowspan="3" align="top">3</td>
<td>Position</td>
<td>Name</td>
</tr>
<tr>
<td>Position</td>
<td>Name</td>
</tr>
<tr>
<td>Position</td>
<td>Name</td>
</tr>
</tbody>
</table>
</div>
When using the calendar as it normally is used, you can see that the days.events object has the data, but I need to access that object, or create my own so I can fill my tables. Is there a simple (or even not so simple) way to do that?
Thanks.
UPDATE: I just went back and read the docs and noticed this
An optional expression that is evaluated on each cell generated for
the year and month views. calendarCell can be used in the expression
and is an object containing the current cell data which you can modify
(see the calendarHelper service source code or just console.log it to
see what data is available). If you add the cssClass property it will
be applied to the cell.
Due to my lack of knowledge, I'm not understanding how to use this to override. If I console.log calendarCell in my calendarController it chokes because that object doesn't exist. If I'm reading this correctly, I can intercept the cell data and modify, but I'm not understanding how.
In this case, RTFM turned out to be the correct answer. Per the docs:
<div ng-controller="CellModifierCtrl as vm">
<ng-include src="'calendarControls.html'"></ng-include>
<mwl-calendar
events="vm.events"
view="vm.calendarView"
view-date="vm.viewDate"
cell-modifier="vm.cellModifier(calendarCell)">
</mwl-calendar>
</div>
goes with this in the controller:
vm.cellModifier = function(cell) {
console.log(cell);
if (cell.label % 2 === 1 && cell.inMonth) {
cell.cssClass = 'odd-cell';
}
cell.label = '-' + cell.label + '-';
};
and voila!, you have access to the data. I'm still trying to figure out how to pass additional data into the function, but I'll open a separate question for that.

How to pass array to html in angularjs1.5.5

How can I pass array Json data from angularjs Controller to html.
Here is my html
<body ng-app="bookApp">
<div ng-controller="bookListCtr">
<table>
<thead>
<tr>
<th>something</th>
<th>something</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td><( item.id )></td>
</tr>
</tbody>
</table>
</div>
</body>
Here is my Angularjs
var bookApp = angular.module('bookApp', []);
bookApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<(');
$interpolateProvider.endSymbol(')>');
});
bookApp.controller('bookListCtr', function ($scope, $http) {
$http.get('http://localhost/client_side/public/book').success(function(data) {
if(data.s_respond === 200){
$scope.items = data.data;
console.log(data.data)
}
});
});
This is Json data After console
s_respond = 200
data = "[{"id":"7","title":"Seven is my lucky number","link":"/api/v1/items/7"},{"id":"8","title":"A Dance with Dragons","link":"/api/v1/items/8"},{"id":"10","title":"Ten ways to a better mind","link":"/api/v1/items/10"},{"id":"42","title":"The Hitch-hikers Guide to the Galaxy","link":"/api/v1/items/42"},{"id":"200","title":"Book title #200","link":"/api/v1/items/200"},{"id":"201","title":"Book title #201","link":"/api/v1/items/201"},{"id":"202","title":"Book title #202","link":"/api/v1/items/202"},{"id":"203","title":"Book title #203","link":"/api/v1/items/203"},{"id":"204","title":"Book title #204","link":"/api/v1/items/204"},{"id":"205","title":"Book title #205","link":"/api/v1/items/205"}]"
I think that you need parse the json
$scope.items = JSON.parse(data.data);
a link that explain that:
https://www.quora.com/How-can-I-convert-JSON-format-string-into-a-real-object-in-JS
There r two tags... meaning 2 column try adding another in Ua body
<body ng-app="bookApp"> <div ng-controller="bookListCtr">
<table>
<thead>
<tr> <th>something</th> <th>something</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items"> <td>{{item.id }}</td>
<td>something else</td>
</tr>
</tbody>
</table>
</div>
</body>

get Data using angularJS

I'm trying to get Data in HTML Table using angularJS, I've splitted the project in 3 parts :
1- Main Part : main.html : which load html Table file and also the Java script(angularJS) (Main.html)
<div class="panel panel-primary">
<div class="panel-heading">Student's List</div>
<div ng-include="'Student_list.html'">
</div>
<script src= "../js/ngMain.js"></script>
2- Html Table : it's Table html tag (Student_list.html)
<table class="table table-borAdherentdered table-hover" id="stdlst">
<thead>
<tr>
<th>Id</th>
<th>Full Name</th>
<th>Email</th>
<th>Birth's Date</th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="std in students">
<td>{{std.Id}}</td>
<td>{{std.Name}}</td>
<td>{{std.Email}}</td>
<td>{{std.BoD}}</td>
<td>{{std.Class}}</td>
</tr>
</tbody>
</table>
3- JS File : load data From mySQL (ngMain.js)
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.GetStudent=function() {
$scope.students=[];
$http.post("Main.php",{'ScriptName':'GetData','ScriptParam':'student'+"|"+'Id'+";"+'Name'+";"+'Email'+";"+'BoD'+";"+'Class',"DataTypeResult":'string'})
.success(function (data,status,headers,config) {
$scope.students=data;
console.log("Get Student List succesfully");
});
}
});
The php script (Main.php) it's working I have tested using REST app with no problem.
My Problem here :
Is that I don't get any Data, only Table Header (BTW :in student Table there is a lot of records) ?
Any idea What 's missing ? or if I m doing it wrong please correct me .
Thanks.
/Koul
I think that the code you posted is incomplete.
There are no ng-app and ng-controller at all and the GetStudent function is never called.
However here there is a working fiddler with mock data that I think will help you.
http://jsfiddle.net/ds7hryn5/2/
HTML:
<div ng-app="myApp">
<div class="panel panel-primary" >
<div class="panel-heading">Student's List</div>
<table class="table table-borAdherentdered table-hover" id="stdlst" ng-controller="myCtrl">
<thead>
<tr>
<th>Id</th>
<th>Full Name</th>
<th>Email</th>
<th>Birth's Date</th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="std in students">
<td>{{std.Id}}</td>
<td>{{std.Name}}</td>
<td>{{std.Email}}</td>
<td>{{std.BoD}}</td>
<td>{{std.Class}}</td>
</tr>
</tbody>
</table>
</div>
</div>
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope','$http',function($scope,$http) {
$scope.GetStudent=function() {
$scope.students=[{
Id:4,
Name:'Name1',
Email:'name1#eee.it',
BoD:'bod1',
Class:'class'
},{
Id:5,
Name:'Name2',
Email:'name2#eee.it',
BoD:'bod2',
Class:'class'
},{
Id:6,
Name:'Name3',
Email:'name3#eee.it',
BoD:'bod3',
Class:'class'
}];
}
$scope.GetStudent();
}]);
It seems to me that your function, $scope.GetStudent, is never called in your controller, thus the data for your table is never fetched.
If $scope.students stays empty, you will see only the headers of your table.
To debug these kinds of issues, it is good practice to watch the network tab in your developer tools of the browser you're using, just to see if your data provider (Main.php) is being called.
In this case I would suspect that it isn't since there is no call to your $scope.GetStudent function in your provided code.
To call the function when the script is loaded, just add a call ($scope.GetStudent()) in your controller just after your function definition.
Example:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.GetStudent=function() {
$scope.students=[];
$http.post("Main.php",{'ScriptName':'GetData','ScriptParam':'student'+"|"+'Id'+";"+'Name'+";"+'Email'+";"+'BoD'+";"+'Class',"DataTypeResult":'string'})
.success(function (data,status,headers,config) {
$scope.students=data;
console.log("Get Student List succesfully");
});
}
$scope.GetStudent();
});
Regards,
Sem

Angular.js smart table loading symbol during ajax call

Using the pipe/ajax plugin example at http://lorenzofox3.github.io/smart-table-website I have been trying to implement an Angular.js smart table with a loading indicator whilst my ajax call is still loading.
angular-boostrap.js
var eposWebAngularStrutsApp = angular.module('eposWebAngularStrutsApp', ['ngResource','smart-table']);
angular-controller.js
eposWebAngularStrutsApp.controller('StoreHealthCheckController', ['$scope','StoreServerHealth', function ($scope, StoreServerHealth) {
//http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/
var ctrl = this;
this.displayed = [];
this.callServer = function callServer(tableState) {
ctrl.isLoading = true;
StoreServerHealth.query(function(result) {
ctrl.displayed = result.data;
ctrl.isLoading = false;
}); //query() returns all the entries
};
}]);
angular-service.js
eposWebAngularStrutsApp.factory('StoreServerHealth', function($resource) {
return $resource('json/storeHealthCheckList.action'); // Note the full endpoint address
});
My JSP...
<table class="table table-striped" st-pipe="mc.callServer" st-table="mc.displayed" ng-controller="StoreHealthCheckController">
<thead>
<tr>
<th>Store</th>
<th>Server</th>
<th>Conn Status</th>
<th>Last Updated</th>
<th>MDI</th>
<th>Last Synched (MDI)</th>
<th>DSM</th>
<th>Last Synched (DSM)</th>
<th>Trading Status</th>
<th>Build</th>
</tr>
</thead>
<tbody ng-show="!mc.isLoading">
<tr ng-repeat="row in mc.displayed">
<td>{{row.locationId}}</td>
<td>{{row.clientId}}</td>
<td>{{row.status}}</td>
<td>{{row.displayLastUpdateTime}}</td>
<td>{{row.replicationStatus}}</td>
<td>{{row.displayLastReplicationSyncTime}}</td>
<td>{{row.dsmReplicationStatus}}</td>
<td>{{row.dsmLastSynchTime}}</td>
<td>{{row.storeTradingStatus}}</td>
<td>{{row.buildVersion}}</td>
</tr>
</tbody>
<tbody ng-show="mc.isLoading">
<tr>
<td colspan="10" class="text-center">Loading ... </td>
</tr>
</tbody>
</table>
But I keep getting an error TypeError: href is null firebug/content/debugger/stackFrame/StackFrame.js.
Can someone let me know what I might be doing wrong here.
Thanks
The comment posted above was the answer to this question. I had forgotten to Alias the controller.

Categories