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;
});
Related
I am attempting to follow a JSFiddle, where a user can click on a <td> item, edit it, then eventually be able to save the changes.
The example uses ng-repeat and all others I have looked at do to where as I am not, I am using data passed from a resolve command in my route folder.
$stateProvider
.state('app.patents.patent', {
url: '/{patentId}',
component: 'patent',
resolve: {
patent: ['patents', '$stateParams', function(patents, $stateParams) {
return patents.find(function(patent){
return patent.id == $stateParams.patentId;
})
}]
}
})
}]);
I have attempted to use data-id (looked at How to retrieve the clicked ElementId in angularjs?), but with no success, as I assume you cannot use the same id twice and my desired functionality requires two elements that ng-show and ng-hide depending on the boolean value passed to them.
I have now got myself in a confused state, not sure which approach to take.
Question
How do I adapt my code that doesn't use ng-repeat to work with this JSFiddle? OR do you know another apporach I can take to achieve the same results?
<tr>
<th class="text-xs-right">Short Name</th>
<td>
<span data-id="123" ng-hide="$ctrl.shortTitle.editing" ng-dblclick="$ctrl.editItem(123)">{{$ctrl.patent.shortTitle}}</span>
<input type="text" data-id="123" ng-show="$ctrl.shortTitles.editing" ng-blur="$ctrl.doneEditing(123)" ng-model="$ctrl.patent.shortTitle"></input>
</td>
</tr>
angular.module('myApp').component('patent', {
templateUrl: 'p3sweb/app/components/patents/views/patent-item.htm',
controller: function() {
var vm = this;
vm.editItem = function (item) {
item.editing = true;
}
vm.doneEditing = function (item) {
item.editing = false;
};
});
As per my understanding regarding your question I have created a jsfiddle, have a look or you can create a jsfiddle with the issue you are facing for better understanding
JSFiddle
<!DOCTYPE html>
<div ng-app ng-controller="myCtrl" class="container">Double-click on the items below to edit:
<button type="button" ng-click="newItem()">Add item</button>
<table>
<tr ng-repeat="item in items">
<td>
<span ng-hide="item.editing" ng-dblclick="editItem(item)">{{item.name}}</span>
<input ng-show="item.editing" ng-model="item.name" ng-blur="doneEditing(item)" autofocus />
</td>
</tr>
</table>
</div>
You can create an array and connect each input to a specific index starting from 0 and then pass that index to your function call.
<tr>
<th class="text-xs-right">Short Name</th>
<td>
<span ng-hide="$ctrl.editing[1]" ng-dblclick="$ctrl.editItem(1)">{{$ctrl.patent.shortTitle}}</span>
<input type="text" data-id="123" ng-show="$ctrl.editing[1]" ng-blur="$ctrl.doneEditing(1)" ng-model="$ctrl.patent.shortTitle"></input>
</td>
</tr>
angular.module('myApp').component('patent', {
templateUrl: 'p3sweb/app/components/patents/views/patent-item.htm',
controller: function() {
var vm = this;
vm.editing=[];
vm.editItem = function (index) {
vm.editing[index] = true;
}
vm.doneEditing = function (index) {
vm.editing[index] = false;
};
});
Demo: http://jsfiddle.net/F7K63/381/
UPDATE: It was because not setting the values for $scope.quantity
I have 3 places where I should ng-repeat 3 different data sources.
I use 3 controllers, from which only the 1st one displays data. The other two can console.log the data, but do not display it.
I really can't understand why everything works for the 1st set of data, but not for the rest, even though the code is pretty much the same for all of them.
js
//this is working
function publisherController($scope, $http) {
//$scope.sortType = 'name'; // set the default sort type
//$scope.sortReverse = false; // set the default sort order
$scope.searchPublisher = ''; // set the default search/filter term
$http.get("/ServiceProxy.aspx?apiPath=api/path1")
.then(function (response) {
$scope.pubNames = response.data;
console.log(JSON.stringify($scope.pubNames));
});
$scope.quantity = 5;
};
// this is not working
var formatController = function ($scope, $http) {
//$scope.sortType = 'name'; // set the default sort type
//$scope.sortReverse = false; // set the default sort order
$scope.searchFormat = ''; // set the default search/filter term
$http.get("/ServiceProxy.aspx?apiPath=api/demand/path2")
.then(function (response) {
$scope.formatNames = response.data;
console.log($scope.formatNames);
});
};
//this is not working
function distributorController($scope, $http) {
//$scope.sortType = 'name'; // set the default sort type
//$scope.sortReverse = false; // set the default sort order
$scope.searchDistributor = ''; // set the default search/filter term
$http.get("/ServiceProxy.aspx?apiPath=api/path3")
.then(function (response) {
$scope.distributorNames = response.data;
console.log(JSON.stringify($scope.distributorNames));
});
};
html
<div class="row" ng-app>
<-- This is working -->
<div ng-controller="publisherController">
<table class="table table-bordered table-striped">
<tbody id="format">
<tr ng-repeat="roll in pubNames | orderBy:sortType:sortReverse | filter:searchPublisher | limitTo:quantity">
<td><input type="checkbox" id="myCheck">{{roll}}</td>
</tr>
</tbody>
</table>
</div>
<-- This is NOT working -->
<div ng-controller="formatController">
<table class="table table-bordered table-striped">
<tbody id="format">
<tr ng-repeat="f in formatNames | orderBy:sortType:sortReverse | filter:searchDistributor | limitTo:quantity">
<td><input type="checkbox" id="myCheck">{{f}}</td>
</tr>
</tbody>
</table>
</div>
<-- This is NOT working -->
<div ng-controller="distributorController">
<table class="table table-bordered table-striped">
<tbody id="distributor">
<tr ng-repeat="d in distributorNames | orderBy:sortType:sortReverse | filter:searchDistributor | limitTo:quantity">
<td><input type="checkbox" id="myCheck">{{d}}</td>
</tr>
</tbody>
</table>
</div>
</div>
I have a static HTML table in which have 2 column one is for employeeID and other is for Employee Name regarding every entry a asp:button appears generated. I want on the click of button it gives me employeeID.
<div ng-app="myApp" ng-controller="myCtrl">
<table border="1" width="100%">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
</tr>
<tr ng-repeat="detail in details" align="center">
<td>{{ detail.EmployeeID }}</td>
<td>{{ detail.EmployeeName }}</td>
<td>
<asp:Button ID="btnDelete" Text="Delete Request" CommandArgument="{{detail.EmployeeID}}" runat="server" OnClick="btnDelete_Click"/>
</td>
</tr>
</table>
Below is script to render value form XML in the table
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$http.get('myDB.xml')
.then(function (response) {
var x2js = new X2JS();
//$scope.details = response.data.UserDetail;
$scope.details = [];
/*setting up the response*/
var data = x2js.xml_str2json(response.data);
$scope.details = data.UserDetail.Detail;
});
$scope.removerequest = function (row) {
$scope.details.splice($scope.delete.indexOf(row), 1);
}
});
XMl
<UserDetail>
<Detail>
<EmployeeID>997857</EmployeeID>
<EmployeeName>Aakash</EmployeeName>
</Detail>
<Detail>
<EmployeeID>999786</EmployeeID>
<EmployeeName>Amit</EmployeeName>
</Detail>
</UserDetail>
Button click code
protected void btnDelete_Click(object sender, EventArgs e)
{
string id=btnApprove.CommandArgument;
Response.Write(id);
var xDoc = XDocument.Load(#"D:\test\myDB.xml");
xDoc.Descendants("Detail")
.Elements("EmployeeID")
.Where(x => x.Value == id)
.Remove();
xDoc.Save(#"D:\test\myDB.xml");
}
how to get td value in command argument form angularJS bind element
you can pass the employeeID like so, ng-click= btnDelete_Click( detail.EmployeeID ) in your button. this takes the scope variable defined by the ng-repeat and passes it as an argument for the function BtnDelete_Click()
So we're developing this angular app with a firebase backend. I am having trouble with this particular function we're implementing. Basically what it does is every time a different option is selected, the showData() function fires to retrieve the relevant data from firebase (and it works). The problem is that the ng-repeat only updates on the first selection change. Successive selection changes are not reflected in the ng-repeat (although the data is retrieved and thus, the model changed).
View:
<div class="container" ng-controller="dataController">
...
<select ng-model="selectedOption" ng-change="showData()">
<option ng-repeat="entry in transactions" ng-value="entry.serial">{{ entry.serial }}</option>
</select>
</div>
<div class="col-md-9">
<table class="table table-hover table-striped table-condensed">
...
<tbody>
<tr ng-repeat="entry in dataHistory">
<td>{{ entry.id }}</td>
<td>{{ entry.timestamp | date:"yyyy MMM dd 'at' h:mm:ssa" }}</td>
<td>{{ entry.amount }}</td>
</tr>
</tbody>
</table>
</div>
Controller:
...
.controller('dataController', ['$scope', '$firebaseArray', function($scope, $firebaseArray) {
...
$scope.showData = function() {
$scope.dataHistory = [];
transfersRef.orderByChild('serial').equalTo($scope.selectedOption).on('child_added', function(snap) {
transactionsRef.orderByKey().equalTo(snap.val().transactionID).on('child_added', function(data) {
var entry = {};
entry = data.val();
entry.id = data.key();
usersRef.child(entry.fromUserId).child('name').once('value', function(nameSnap) { entry.fromUsername = nameSnap.val(); });
usersRef.child(entry.toUserId).child('name').once('value', function(nameSnap) { entry.toUsername = nameSnap.val(); });
console.log('entry: \n' + entry);
$scope.dataHistory.push(entry);
});
});
};
}])
...
Try applying $scope.$apply() after $scope.dataHistory.push(entry); in your code.
This is because your array updating code maybe outside the angular digest cycle.
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>