AngularJS set html properties - javascript

we are pretty bloody beginners with JavaScript and AngularJS, but the scenarios is pretty simple. We want to set html properties received from a REST service.
This is our profileController.js:
angular
.module('app')
.controller('profileController', ['$scope', '$http', '$window', function($scope, $http) {
// REST service works properly
var resource = 'http://localhost:8080/user';
$http.get(resource).then(function(result){
// logs right json
console.log(result);
// no effect
$scope.content = result.data.toString();
// no effect
if(!$scope.$$phase) {
$scope.$apply();
}
});
} ]);
profile.html
<div>
<div class="container">
<br><br><br>
<h2 class="sub-header">Profile</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Forename</th>
<th>Name</th>
<th>Role</th>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{profile.data}}</td>
<!-- Doesn't work as well
<td>{{profile.forename}}</td>
<td>{{profile.lastname}}</td>
<td>{{profile.role}}</td>
<td>{{profile.email}}</td>-->
</tr>
<div id="container" ng-controller="profileController">
<content-item forename="item"></content-item>
</div>
</tbody>
</table>
</div>
</div>
</div>
The REST service works properly and sends the json back, the log outputs in the JavaScript console are right, just the setting in html doesn't work and we have absolutely no clue.
Thanks in advance!

Consider this Plunk.
app.controller("myController", [
"$scope",
function($scope){
$scope.content = [
{
"firstname": "Natalie",
"lastname": "Portman",
"role": "Accountancy",
"email": "n.p#email.com"
},
{
"firstname": "Johnny",
"lastname": "Depp",
"role": "Sales Management",
"email": "j.d#email.com"
},
{
"firstname": "Kevin",
"lastname": "Costner",
"role": "Crisis control",
"email": "k.c#email.com"
},
];
}]);
Where the above $scope.content is a hardcoded simulation of your $scope.content = result.data;.
And usage:
<tr ng-repeat="profile in content">
<td>#</td>
<td>{{profile.firstname}}</td>
<td>{{profile.lastname}}</td>
<td>{{profile.role}}</td>
<td>{{profile.email}}</td>
</tr>
Check the Plunk for the complete code.
PS: I changed the {{profile.data}} to # for the example, as I don't know what that's supposed to be.

Try this
Check your ng-controller and ng-app too, this step in the angular tutorial should be fine for this.
Here, in your code, the ng-controller should be at least in the table tag i.e
<div>
<div class="container">
<br><br><br>
<h2 class="sub-header">Profile</h2>
<div class="table-responsive">
<table class="table table-striped" ng-controller="profileController">
<thead>
<tr>
<th>#</th>
<th>Forename</th>
<th>Name</th>
<th>Role</th>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{content}}</td>
<!-- Doesn't work as well
<td>{{content.forename}}</td>
<td>{{content.lastname}}</td>
<td>{{content.role}}</td>
<td>{{content.email}}</td>-->
</tr>
<div id="container">
<content-item forename="item"></content-item>
</div>
</tbody>
</table>
</div>
</div>

convert
$scope.content = result.data.toString();
to this:
$scope.content = result.data;
And if you want to print the data inside
<td>{{profile.data}}</td>
you have to change position of controller in html tag..

Related

Angular JS Display Response Values

I'm trying to display data from one page to another in Angular JS. Using displayResponse in Firefoxes Console, the Response data seems to be retrieved however I'm having trouble trying to display the values on the page which is troublesome since a Team member was able to get them to display properly on other pages on the site.
Here is the Code so far (I have removed chucks of the script to save screen space. These bits of code are not relevant to the issue afaik):
var app = angular.module("myApp", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/ViewSalesRecords', {
templateUrl: 'view-sales-records.html',
controller: 'salesRecordController'
}).
when('/ViewSingleSale', {
templateUrl: 'view-single-sale.html',
controller: 'salesRecordController'
});
});
app.controller('salesRecordController', ['$scope', '$http', function($scope, $http) {
$scope.displaySingleSale = function(sale_id) {
$http.post('read_sale.php', {
'sale_id': sale_id
})
.then(function(response) {
$scope.singleSalesRecord = response.data;
console.log($scope.singleSalesRecord);
})
}
$http.get("read_sale.php")
.then(
function(response) {
$scope.salesRecords = response.data;
}
)
}]);
<head>
<link href="./styles/style.css" rel="stylesheet">
</head>
<table class="table table-hover" data-ng-model="sale_id">
<p><strong>Sale ID: {{displayResponse}} </strong> </p>
<p><strong>Sale Date: </strong> </p>
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Item Total</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="s in singleSalesRecord">
<td>{{s.product_id}}</td>
<td>{{s.product_name}}</td>
<td>{{s.quantity}}</td>
<td>${{s.product_price}}</td>
</tr>
</tbody>
</table>
<p><strong>Total: ${{s.orderTotal}}</strong></p>
The page that is sending the data
<head>
<link href="./styles/style.css" rel="stylesheet">
</head>
<div>
<input class="form-control searchBar" data-ng-model="searchText.sale_id" type="text" placeholder="Search sales by Sale ID">
<table class="table table-hover">
<thead>
<tr>
<th>Sale ID</th>
<th>Total items</th>
<th>Total price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="s in salesRecords | filter:searchText:strict">
<td>{{s.sale_id}}</td>
<td>{{s.TotalItems}}</td>
<td>${{s.orderTotal}}</td>
<td>
<button class="btn btn-primary">View</button>
<button class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
So wall of text taken into consideration, what am I doing wrong? I will admit I'm not too familiar with AngularJS so this might be a very amateur mistake on my part.
I figured out that the problem was that the values that I wanted to transfer were been wiped when I moved to another page. So I decided to simply display them on the first page instead hyperlinking to another.

Displaying JSON content in table rows using angularjs and codeigniter

I'm just trying to fetch contents from server and display it in a table using Angularjs. I'm been trying this from a while, but did not got any solution yet. Btw, I'm working on CodeIgniter framework.
Here is my CodeIgniter controller;
public function list_agents() {
if($this->is_logged_in ()) {
$agents = $this->generic_model->general_fetch('agent_master');
echo json_encode($agents);
}
else {
redirect(base_url());
}
}
In the above code, instead of echo I used print, print_r also.. But still its not working.
Here is my js file function;
(function () {
var addApp = angular.module('agentApp', ['ngRoute']);
addApp.controller('agentAddController', function ($scope, $http, growl) {
$scope.receivedData = [];
$http({
method : 'POST',
url : 'agent/list_agents',
headers : {
"Content-Type" : "application/json"
}
}).then(function (data) {
$scope.receivedData = JSON.parse(data);
});
});
})();
And in this above code I used with and without JSON.parse function. Didn't got the correct result.
Here is my view;
<section class="content" ng-app="agentApp" ng-controller="agentAddController">
<div class="row">
<div class="col-md-12">
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Manage Agents</h3>
</div>
<div class="box-body">
<table class="table table-striped table-bordered" id="agents_table">
<thead>
<tr>
<th>Sl No.</th>
<th>Agent Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<div ng-repeat="data in receivedData">
<tr>
<td>{{ $index + 1 }}</td>
<td>{{ data.agent_name }}</td>
<td><button class="btn btn-warning btn-xs"><i class="fa fa-trash" aria-hidden="true"></i></button></td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
<th>Sl No.</th>
<th>Agent Name</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</section>
I know if I put ng-repeat inside tr tag I'll get the perfect result, but I don't want to do that because, I'm working with adminLTE. So there is a function DataTable() in adminLTE where it'll apply search and pagination to the table. If I give ng-repeat to tr, these functionalities can not be added.
Try: $scope.receivedData = JSON.parse(data.data);
The response object is not only the data itself, that's why the 5 rows. It gives back, data, headers, status, etc...
https://docs.angularjs.org/api/ng/service/$http

How to consume JSON array in AngularJS?

What i trying to do here is, i want to consume the JSON that i produce using Spring Restful WebService, which is looked like this :
[
{
"userid": 1,
"firstName": "kevin",
"lastName": "buruk",
"email": "pucuk#ubi.com"
},
{
"userid": 2,
"firstName": "helm",
"lastName": "krpuk",
"email": "helmkrupuk#gmail.com"
},
{
"userid": 3,
"firstName": "batok",
"lastName": "kelapa",
"email": "batokkelapa#gmail.com"
}
]
That JSON is produce by this function in my Java Spring MVC Controller, which is looked like this :
SpringController.java
#RestController
#RequestMapping("/service/")
public class SpringServiceController {
UserService userService = new UserService();
#RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userService.getAllUsers();
return users;
}
}
And i am about to consume the JSON value into angular table, so i do store the JSON value in angular object in the scope, here is my Javascript code. i named this file app.js
app.js
function Hello($scope, $http) {
$http.get('http://localhost:8080/SpringServiceJsonSample/service/').
success(function(data) {
$scope.users = data;
});
}
and here is my html page. i named it index.html
index.html
<html ng-app>
<head>
<title>Angular Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="Hello">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{user.userid}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
</tr>
</tbody>
</div>
</body>
</html>
What i missed here? i won't show anything. Before this i was trying to consume the JSON that i only have one record, it work properly. But this time i trying to consume the array, and i failed. What i missed here? is it the JSON or my javascript?
First of all, you have to use latest version of angular. Now, it's 1.4.5 with more performance optimizations and features.
About your question: error in html code. Here's the fixed version
function Hello($scope, $http) {
$scope.users = [
{
"userid": 1,
"firstName": "kevin",
"lastName": "buruk",
"email": "pucuk#ubi.com"
},
{
"userid": 2,
"firstName": "helm",
"lastName": "krpuk",
"email": "helmkrupuk#gmail.com"
},
{
"userid": 3,
"firstName": "batok",
"lastName": "kelapa",
"email": "batokkelapa#gmail.com"
}
]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app>
<table ng-controller="Hello">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{user.userid}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
</tr>
</tbody>
</table>
</body>
As you can see, I fixed it with adding only one html tag!

Getting and passing MVC Model data to AngularJS controller

I'm pretty new to AngularJS and I'm at a loss here.
Right now my MVC program uses Razor to display all the data in my .mdf database (i.e: #Html.DisplayFor(modelItem => item.LastName) ). However, I want to go mostly Angular. I am trying to use ng-repeat to display all of the Model data, but I am not sure how to pass that Model data to the Angular controller and then use it. I have tried serializing the Model to JSON in my ng-init, but I don't think I'm doing it right (obviously).
Here is my code:
// controller-test.js
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope) {
$scope.init = function (firstname) {
$scope.firstname = firstname;
}
});
<!-- Index.cshtml -->
#model IEnumerable<Test.Models.Employee>
#{
ViewBag.Title = "Index";
}
<div ng-app="myModule">
<div ng-controller="myController" ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
<table>
<tr ng-repeat= <!--THIS IS WHERE I'M STUCK -->
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
#Scripts.Render("~/Scripts/angular.js")
I'm not sure exactly what I should be repeating on to get the FirstName from the serialized Model. I feel like I have all the pieces, but just unsure how to connect them.
If you have the key firstName on your Json object like:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
}
You can do it in the following way.
On your controller:
myApp.controller('myController', function ($scope) {
$scope.init = function (employees) {
$scope.employees = employees;
}
});
On your view:
<table>
<tr ng-repeat= "employee in employees">
<td>{{ employee.firstName }}<td>
</tr>
</table>
Thank you to darkstalker_010!
What I was confused was with how my Angular controller file interacted with the view. All I had to do was simply treat my angular {{ }} data in my .cshtml file as if I were trying to access the Model data normally (i.e. model.AttributeName)
So here is the updated, working code:
// controller-test.js
var myApp = angular.module('myModule', []);
myApp.controller('myController', function ($scope) {
$scope.init = function (employees) {
$scope.employees= employees;
}
});
<!-- Index.cshtml -->
#model IEnumerable<Test.Models.Employee>
#{
ViewBag.Title = "Index";
}
<div ng-app="myModule">
<div ng-controller="myController" data-ng-init="init(#Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Title</th>
<th>Department</th>
<th>Email</th>
</tr>
<tr ng-repeat="e in employees">
<td>{{e.FirstName}}</td>
<td>{{e.LastName}}</td>
<td>{{e.Title}}</td>
<td>{{e.Department.DepartmentName}}</td>
<td>{{e.Email}}</td>
</tr>
</table>
</div>
</div>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
#Scripts.Render("~/Scripts/angular.js")
Here is what it looks like sans formatting:

Accessing a JSON in AngularJS using ng-repeat

<table class="table table-striped" >
<thead>
<tr>
<th>Number</th>
<th>Zeroes</th>
</tr>
</thead>
<tbody ng-controller="ViewData as viewAll">
<tr ng-repeat="pop in viewAll.number">
<td>{{pop.number}}</td>
<td>{{pop.zeroes}}</td>
</tbody>
</table>
I have this table and I'm trying to get data to be outputted in it.
app.controller('ViewData', ['$http', '$scope',
function($http,$scope) {
$scope.viewAll = this;
$http.get('/someurl').success(function(data) {
$scope.viewAll.number = data;
});
}]);
This my controller getting the data.
{"number": {
"4": {
"zeroes": "5"
},
"5": {
"zeroes": "6"
},
"10": {
"zeroes": "7"
}}
And this is the data that /someurl is giving out to me.. Is there any way I can be able to handle this so I can be able to show it outside the table.
Thanks in advance for any kind of help given!
try:
<table class="table table-striped" >
<thead>
<tr>
<th>Number</th>
<th>Zeroes</th>
</tr>
</thead>
<tbody ng-controller="ViewData as viewAll">
<tr ng-repeat="{key, value} in viewAll.number">
<td>{{key}}</td>
<td>{{value.zeroes}}</td>
</tbody>
</table>
app.controller('ViewData', ['$http', '$scope',
function($http,$scope) {
var self = this;
$http.get('/someurl').success(function(data) {
self.number = data;
});
}]);

Categories

Resources