angular ng-repeat not working as expected - javascript

<body ng-app="myApp">
<div ng-controller="customersCtrl">
<table>
<tr ng-repeat="res in customers">
<td>{{ $index + 1 }}</td>
<td>{{ res.Name }}</td>
<td>{{ res.City }}</td>
</tr>
</table>
</div>
</body>
var myApp = angular.module('myApp', []);
myApp.controller("customersCtrl", function ($scope,$http) {
$http.post('Default.aspx/Getdata', { data: {} })
.success(function (response) {
$scope.customers = response.d;
})
.error(function (data, status, headers, config) {
alert(status+"-------"+data);
});
});
server side function:
[WebMethod]
public static string Getdata()
{
List<customors> people = new List<customors>{
new customors{Name = "biss",City="Lebanon"},
new customors{Name = "jiji",City="America"}
};
JavaScriptSerializer serialiser = new JavaScriptSerializer();
string json = serialiser.Serialize(people);
return json; // [{"Name":"biss","City":"Lebanon"},{"Name":"jiji","City":"America"}]
}
public class customors
{
public string Name{get;set;}
public string City{get;set;}
}
but No result is being displayed . what i am doing wrong ?

Replace your succes function with this:
.success(function (response) {
$scope.customers = JSON.parse(response.d);
})
Your objects are in string format, it will never be able to find .Name if 'Name' is a string. Parsing your response will fix this.
As RGraham stated, this is not ideal. You want to handle this correctly on your server's side.

Related

How to loop in AngularJs

I am new to Angular, maybe is a fool question.
I have a result from my AngularJs and I return an Array of values:
This is the code:
$scope.searchTitle = function () {
$http.post('/svn/cms2/branches/create_function/cms/includes/find.php', {
name_title: $scope.title
})
.success(function (result) {
console.log(result);
$scope.resultName = result;
$scope.ok = "we post";
})
.error(function (data, status) {
console.log(data);
});
};
And now i have the resultName in the html and i can see the result if i do this:
<p>{{ resultName[0].article_titile }}</p>
Question:
I want to display all the array. How can I display all?
P.S.:
I use this and it is not work
<tr ng-repeat="i in [3] | toRange" >
<td>{{ resultName[i].article_titile }}</td>
</tr>
But is not working
You need to use an iterator variable (e.g. result) with your resultName array in your ng-repeat:
<tr ng-repeat="result in resultName | toRange" >
<td>{{ result.article_titile }}</td>
</tr>

ng-repeat in AngularJs doesnt show data in table but show empty rows

I'm using AngularJs in Asp.net Mvc5 for create single page application.
I have a problem , when i use ng-repeat for show data in table , my data doesn't show in table but show empty rows
This is my Home Controller
angularFormsApp.controller("HomeController",
function ($scope, $location, DataService) {
DataService.getEmployees().then(
function (results) {
$scope.names = results.data;
console.log(results.data);
console.log("This is console");
},
function (error) {
// on error
alert("error read data" + error);
}
);
});
This is my DataService
angularFormsApp.factory('DataService',
function ($http) {
var getEmployees = function () {
return $http.get("Employee/GetEmployees");
};
return {
getEmployees: getEmployees
};
});
This is My Html Page
<div ng-app="angularFormsApp">
<div ng-controller="HomeController">
{{ Namef }}
<table class="table table-hover ">
<thead>
<tr>
<th>Name Employee</th>
<th>Note</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in names">
<td>{{ item.FullName }}</td>
<td>{{ item.Note }}</td>
<td>
Edite
Delete
</td>
</tr>
</tbody>
</table>
</div>
</div>
This is My EmployeeController
public class EmployeeController : Controller
{
// GET: Employee
DataLayer.WebapplicationContext db = new DataLayer.WebapplicationContext();
public ActionResult GetEmployees()
{
var data = db.Employees.ToList();
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
var jsonResult = new ContentResult
{
Content = JsonConvert.SerializeObject(data, camelCaseFormatter),
ContentType = "application/json"
};
return jsonResult;
//return new HttpStatusCodeResult(404, "Our custom error message...");
}
When i run this project i saw empty rows , it's above picture show my problem.
Picture
And this is console log enter image description here
I'm try this code and solve it my problem.In EmployeeController change ActionResult to JsonResult
public JsonResult GetEmployees()
{
using (WebapplicationContext Obj = new WebapplicationContext())
{
List<Employee> Emp = Obj.Employees.ToList();
return Json(Emp, JsonRequestBehavior.AllowGet);
}
}

How can I pass my viewmodel data from my view to my controller?

Currently, my view looks something like:
#using (Html.BeginForm("CreateUser", "Home", FormMethod.Post))
{<form ng-controller="MyController">
<table cellpadding="2" cellspacing="2">
<tr>
<td>#Html.LabelFor(model => model.FirstName) </td>
<td>#Html.TextBoxFor(model => model.FirstName, new { ng_model = "user.firstName" }) </td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.LastName) </td>
<td>#Html.TextBoxFor(model => model.LastName, new { ng_model = "user.lastName" })) </td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" ng-click="addUser()" /></td>
</tr>
</table>
</form>
}
My Controller (on ASP.NET MVC side):
[HttpPost]
public ActionResult Create(UsersViM usersVM)
{
//Sets the model equal to viewmodel
//Saves the name in session and redirects to previous view with new list of names.
}
I am wondering, what data should I be passing from my view to my controller? That is, how do I pass my model from my view to my controller? How do I set that up in angular?
$scope.addUser = function() {
var data = {
//user.firstname, user.lastname but how does angular know what user is?
//User is defined as the Model on the ASP.NET MVC side.
};
$http
.post('Home/Create', data)
.success(function(data, status, headers, config) {
})
.errors(function(data, status, headers, config) {
});
};
$scope.addUser = function () {
$http
.post('Home/CreateUser', usersViewModel)
.success(function (data, status, headers, config) {
successFn();
})
.errors(function (data, status, headers, config) {
errorFn();
});
};
Your back-end model fields should be same as like front-end model fields so that the mapping will not generate an error.
Suppose if you have defined you scope as mentioned below then define the user property so that angular can bind it with ng-model properties.
function MyController($scope) {
$scope.user= {};
$scope.addUser= function() {
console.log(this.user);
......
};
}
When the above form is submitted $scope.addUser will contain an object of your form which can then be passed in your http post request. e.g:
Object {firstName: "Test First Name", lastName: "Test Last Name"}

AngularJS : directive does not update scope after $http response in parent scope

I got this directive:
.directive('studentTable', [function() {
return {
restrict: 'A',
replace: true,
scope: {
students: "=",
collapsedTableRows: "="
},
templateUrl: 'partials/studentTable.html',
link: function(scope, elem, attrs) {
...
}
}
}
Template:
<table class="table">
<thead>
<tr>
<th><b>Name</b></th>
<th><b>Surname</b></th>
<th><b>Group</b></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="student in students track by $index">
<td>{{ student.name }}</td>
<td>{{ student.surname }}</td>
<td>{{ student.group }}</td>
</tr>
</tbody>
</table>
Use directive in my html like this:
<div student-table students="students"
collapsedTableRows="collapsedTableRows"></div>
And the parent controller:
.controller('SchoolController', ['$scope', 'User', function($scope, User){
$scope.students = [];
$scope.collapsedTableRows = [];
$scope.search = function(value) {
if(value) {
var orgId = $state.params.id;
var search = User.searchByOrg(orgId, value);
search.success(function (data) {
$scope.students = data;
$scope.collapsedTableRows = [];
_(data).forEach(function () {
$scope.collapsedTableRows.push(true);
});
});
}
}
}])
Now at the beginnig, the table is empty, because no users in students array. After I click search, and get list of students object, I put them to scope variable, but the directive does not update, neither it find change in model (scope.$watch('students',...). What am I missing?
P.S. If I simulate the data using $httpBackend, directive works as it should.
Please make sure that data object returning array of student because somtimes you have to use data.data that simple demo should helps you:
http://plnkr.co/edit/UMHfzD4oSCv27PnD6Y6v?p=preview
$http.get('studen.json').then(function(students) {
$scope.students = students.data; //<-students.data here
},
function(msg) {
console.log(msg)
})
You should try changing the controller this way
...
$scope.$apply(function() {
$scope.students = data;
})
...
This will start a digest loop, if it's not already in progress.
Another form that will do almost the same thing is this:
...
$scope.students = data;
$scope.$digest()
...
PS:
The first method is just a wrapper that execute a $rootScope.$digest() after evaluating the function, considering that a $digest evaluates the current scope and all it's children calling it on the $rootScope is pretty heavy.
So the second method should be preferred if it works.

How to properly iterate over an array elements with Angular JS?

I want to render a table adding row per each objects in an array.
I got a Controller like:
app.controller('SignUpController',function ($scope, $http) {
var that = this
that.users = []
that.queryUsers = function() {
console.log("I'm being triggered")
$http.get("/existingUsers").
success(function (data,status,headers,config) {
console.log(data)
that.users = data
console.log(that.users)
}).
error(function (data,status, headers, config) {
console.log(status)
})
}
})
And the table markup:
<table class="table table-bordered">
<th ng-repeat="th in ['mail','Administrador','Miembro desde']">{{th}}</th>
<tr ng-repeat="p in signup.users">
<td>{{p._id}}</td>
<td>{{p.mail}}</td>
<td>{{p.admin}}</td>
</tr>
</table>
Ttable is within a div with ng-controller="SignUpController as signup". When I click a button I trigger queryUsers actually seein results in browser console:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
Both mail and _id are existing attributes per each object.
So the AJAX is being done and the array I should be iterating and rendering to HTML rows actually exists and is populated, but no rows are shown.
Why?
Edit
I tried not modifying the scope:
app.controller('SignUpController', function ($scope,$http) {
$scope.users = []
$scope.queryUsers = function() {
console.log("I'm being triggered")
$http.get("/existingUsers").
success(function (data,status,headers,config) {
console.log(data)
$scope.users = data
console.log($scope.users)
}).
error(function (data,status, headers, config) {
console.log(status)
})
}
})
<div class="tab-pane" id="usecase11" ng-controller="SignUpController">
<h3>Colaboradores</h3>
<div class="row">
<div class="col-sm-6">
<table class="table table-bordered">
<th ng-repeat="th in ['mail','Administrador','Miembro desde']">{{th}}</th>
<tr ng-repeat="p in users">
<td>{{p._id}}</td>
<td>{{p.mail}}</td>
<td>{{p.admin}}</td>
<td style="border:none;"><a class="close" ng-click="">$</a></td>
<td style="border:none;"><a class="close" ng-click="">*</a></td>
</tr>
</table>
</div>
</div>
</div>
However, again I can see such array printed at browser console but nothing rendered to HTML
Here is the evidence that queryUsers is being called and that $scope.users is getting something after it.
Something interesting is that I got: {{users}} right after the table and it's displaying an empty array.
Just in case this is the GET handling server code:
app.get('/existingUsers',function (request, response) {
membersCollection.find({},{"password":0}, function (err, data) {
if (err) response.send(404)
else {
data.toArray(function (err, docs) {
if (err) {
console.log(error)
response.send("Error")
}
response.send(JSON.stringify(docs, null, 4))
})
}
})
}
You don't modify the $scope. Here is the corrected code:
app.controller('SignUpController',function ($scope, $http) {
$scope.users = []
$scope.queryUsers = function() {
console.log("I'm being triggered")
$http.get("/existingUsers").
success(function (data,status,headers,config) {
console.log(data)
$scope.users = data
console.log($scope.users)
}).
error(function (data,status, headers, config) {
console.log(status)
})
}
})
HTML:
<table class="table table-bordered">
<th ng-repeat="th in ['mail','Administrador','Miembro desde']">{{th}}</th>
<tr ng-repeat="p in users">
<td>{{p._id}}</td>
<td>{{p.mail}}</td>
<td>{{p.admin}}</td>
</tr>
</table>

Categories