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:
Related
I have the following function which is fetching custom HTML template and passing some values into the scope to generate 'report table'. Because the template is not visible to the user but processed output is directly sent to another function I used $compile function.
It seems that values passed into the $scope are processed correctly but i am not able to get pure HTML result.
I tried to do it by this way:
var templateUrl = $sce.getTrustedResourceUrl('report.html');
$templateRequest(templateUrl).then(function(template) {
$scope.rows = reportData;
var compTest = $compile(template)($scope);
console.log(compTest); //IT RETURNS A LOT OF VALUES BUT NOT HTML OUPUT OF THE PROCESSED TEMPLATE
}, function() {
// An error has occurred
});
Many thanks for any advice.
Results is following:
HTML content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Report</title>
</head>
<body>
<table>
<thead>
<td>
</td>
<td>
Breakfast
</td>
<td>
Lunch
</td>
<td>
Dinner
</td>
<td>
Snack
</td>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>TEST</td>
<td>40</td>
<td>20</td>
<td>30</td>
<td>10</td>
</tr>
</tbody>
</table>
</body>
</html>
$compile will return a function which will then be executed by scope which in turn will returns a jQlite wrapped DOM object. So you can use outerHTML to get the Template string
or
You can use $interpolate as shown below
Demo
angular.module('myApp', []);
angular
.module('myApp')
.controller('MyController', MyController);
function MyController($scope, $compile, $interpolate) {
var template = '<a ng-click="handler()">click handler</a>';
this.tmpl = $compile(template)($scope)[0].outerHTML;
this.tmplInt = $interpolate(template)($scope);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyController as MC">
<p><b>using $compile along with outerHTML </b>{{MC.tmpl}}</p>
<p><b>using $interpolate </b>{{MC.tmplInt}}</p>
</div>
</div>
This is for an assignment. Here table contains book details which contains book name, author, price, ISBN and category. When user click on book name it should redirect to order page displaying book name, author and price.
BookPage.html
<script type="text/javascript" src="book.js">
<body ng-app="mymodule" >
<div ng-controller="myController" >
<table border=2>
<thead>
<tr>
<th>ISBN</th>
<th>NAME</th>
<th>AUTHOR</th>
<th>CATEGORY</th>
<th>PRICE</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books">
<td>{{ book.ISBN }}</td>
<td >{{ book.Name }}</td>
<td>{{ book.Author }}</td>
<td>{{ book.Category }}</td>
<td>{{ book.price }}</td>
</tr>
</tbody>
</table>
**books.js**
var myapp = angular.module('mymodule', []);
myapp.controller("myController", function($scope, $http,$window) {
$http.get("https://api.myjson.com/bins/p4ujn").then(function(response) {
$scope.books = response.data;
$scope.getdetail=function(){
$scope.getbookdetail=this.book;
$window.location.href = "orderpage.html";
}
});
});
Page to be redirected when user click on book name.
orderpage.html
<script type="text/javascript" src="book.js"></script>
<body ng-app="mymodule" >
<div ng-controller="myController" >
{{getbookdetail.Name}}<br>
{{getbookdetail.Author}}
{{getbookdetail.price }}<br>
</div>
</body
This is my code. It display nothing, just a blank page.
You can use a Service or factory to share the data across the controllers.
DEMO
var app = angular.module("clientApp", [])
app.controller("TestCtrl",
function($scope,names) {
$scope.names =[];
$scope.save= function(){
names.add($scope.name);
}
$scope.getnames = function(){
$scope.names = names.get();
}
}
);
app.factory('names', function(){
var names = {};
names.list = [];
names.add = function(message){
names.list.push({message});
};
names.get = function(){
return names.list;
};
return names;
});
<!doctype html>
<html >
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="clientApp">
<div ng-controller="TestCtrl">
<input type="text" ng-model="name">
<button ng-click="save()" > save</button>
</div>
<div ng-init="getnames()" ng-controller="TestCtrl">
<div ng-repeat="name in names">
{{name}}
</div>
</div>
</body>
</html>
Apart from service/factory , you can go for other options like localStorage and rootScope, but those are not recommended ways.
You should use factory/Services, localStorage, routeParams or Child Parent controllers
I have a view which displays List of my database and it works!
All I want to do is to pass a variable named "search1" from view to server side Controller Thats ALL!
View
<section data-ng-controller="AllsController" data-ng-init="find()">
<div class="page-header">
<h1>Alls</h1>
</div>
<div class="Search">
<select data-ng-model="search1" id="search">
<option value="Model1">Jeans</option>
<option value="Model2">Shirts</option>
</select>
</div>
<br></br><br></br>
<h2>Result Section</h2>
<div class="list-group">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Created</th>
<th>User</th>
<th>Brand</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="all in alls">
<td data-ng-bind="all.created | date:'medium'"></td>
<td data-ng-bind="all.user.displayName"></td>
<td data-ng-bind="all.name"></td>
<td data-ng-bind="all.color"></td>
</tr>
</tbody>
</table>
</div>
Client Controller
angular.module('alls').controller('AllsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Alls', 'Jeans', function($scope, $stateParams, $location, Authentication, Alls, Jeans) {
$scope.find = function() {
$scope.alls = Alls.query();
}; }]);
Service
angular.module('alls').factory('Alls', ['$resource',
function($resource) {
return $resource('alls/:allId', { allId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}]);
Server Controller
exports.list = function(req, res) {
var search1 = req.search1 ;
if (search1 === 'Jeans' )
{
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
res.jsonp(jeans);
});
} }
Server Route
module.exports = function(app) {
var alls = require('../../app/controllers/alls.server.controller');
app.route('/alls')
.get(alls.list);}
I should be able to see Jeans Model when it is chosen but it does not show me Jeans Model
I think I have not passed "search1" to the server Controller properly and I need to change my client Controller or Server Route;
But I do not know how!
Any idea or example would be helpful,
Thanks!
I think you need to change
var search1 = req.search1;
to
var search1 = req.params.search1;
I am trying to pass a php Laravel array of objects with the name $event to my javascript part of the app and I am having issues with looping through the results later on.
Basically what I am doing is this
$events = Event::orderBy('id', 'DESC')->orderBy('resolved', 'desc')->get(); //get events
return View::make('events.index', compact('events')); //pass events to view
And then this is my view
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var myevents = JSON.parse('<?php echo json_encode($events) ?>');
</script>
<div class="col-sm-12" ng-app="myApp2" ng-controller="checkboxController">
<table class="table" id="keywords" cellspacing="0" cellpadding="0">
<tr ng-repeat="event in myevents" >
<td> {{event.category}}</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</div>
</table>
</div>
</div>
<script src="http://dsproject.dev:8000/js/jquery-1.11.1.min.js"></script>
<script src="http://dsproject.dev:8000/js/bootstrap.min.js"></script>
<script src="http://dsproject.dev:8000/js/checkboxes.js"></script>
</body>
</html>
This is my controller
var myApp2 = angular.module('myApp2',[]);
myApp2.controller('checkboxController', ['$scope', function($scope) {
//var events = [];
// $scope.some = 'hehehhehehe';
//events.($scope.event);
$scope.myevents = myevents;
console.log($scope.myevents);
/*$scope.toggle = function(id) {
alert(id);
};*/
}]);
The output I get is just {{event.category}} with no value at all. When I do console.log(myevents) or console.log($scope.myevents) in my controller I get the array of objects displayed in the console like this
What am I doing wrong and how would I fix this?
The {{ curlies are being parsed by laravel, you have to change interpolation in angular.
myApp2.config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
});
and then use {[{ and }]} for the angular part of variables.
I am using angularjs 1.2.8 with grails 2.3.4 backend. I am providing a Restful Api over the grails Resources tag.
I have a view were I load the data:
<div class="container main-frame" ng-app="testapp"
ng-controller="searchController" ng-init="init()">
<h1 class="page-header">Products</h1>
<table class="table">
<thead>
<tr>
<th width="25px">ID</th>
<th>TITLE</th>
<th>PRICE</th>
<th>Description</th>
<th width="50px"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="p in product by $id">
<td>{{p.id}}</td>
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td>{{p.description}}</td>
<!-- ng-show="user.id &&user.id==e.user_id" -->
</tr>
</tbody>
</table>
<!-- ng-show="user.username" -->
<p>
</div>
I am using the searchController to load the data:
testapp.controller("searchController", function($scope, $rootScope, $http, $location) {
var load = function() {
console.log('call load()...');
var url = 'products.json';
if ($rootScope && $rootScope.appUrl) {
url = $rootScope.appUrl + '/' + url;
}
$http.get(url)
.success(function(data, status, headers, config) {
$scope.product = data;
angular.copy($scope.product, $scope.copy);
});
}
load();
});
However in my postgresql db there is data available, but I only get:
and no expection at all:
Any suggestions what I can do to check that?
PS.: Controller is loaded!
UPDATE
Using
<tr ng-repeat="p in product track by p.id">
I am getting an error:
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.8/ngRepeat/dupes?p0=p%20in%20product%20track%20by%20p.id&p1=undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:6:449
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:184:445
at Object.fn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:99:371)
at h.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:100:299)
at h.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:103:100)
at f (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:67:98)
at E (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:71:85)
at XMLHttpRequest.v.onreadystatechange (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:72:133) angular.js:9413
UPDATE2
The json representation looks like that:
[{"class":"com.testapp.Product.BasicProduct","id":1,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":5.0,"title":"Product1"},{"class":"com.testapp.Product.BasicProduct","id":2,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":75.0,"title":"Product2"},{"class":"com.testapp.Product.BasicProduct","id":3,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":50.0,"title":"Product3"},{"class":"com.testapp.Product.BasicProduct","id":4,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":25.0,"title":"Product4"},{"class":"com.testapp.Product.BasicProduct","id":5,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":15.0,"title":"Product5"}]
Fix the ngRepeat syntax:
<tr ng-repeat="p in product track by p.id">