Reputation: 2711
I know that you can initailise values from an angular controller in a div like this: View:
<div ng-controller="SimpleController">
<ul>
<li ng-repeat="cust in customers">
{{cust.name}} - {{cust.city}}
</li>
</ul>
</div>
Controller:
function SimpleController($scope) {
$scope.customers = [
{ name: 'Jane', city: 'New York' },
{ name: 'John', city: 'Chicago', }
];
}
But lets say that i want to get the data from a controller (that maybe fetches data from a db) and receive its value in $scope.customers?
Have a look at this method:
public ? PassThisToAngular()
{
var customer = new List<Customer>()
{
new Customer() {Name = "Pauly-D", City = "New Jersey"},
new Customer() {Name = "Snooki", City = "New Jersey"}
};
return ?
}
Can I call this method from my angular-controller and store its values in @scope.customers? Thank you!
Upvotes: 1
Views: 1324
Reputation: 2898
Please check below code, it will help you.
In your script side:
<script>
var SimpleController = function ($scope, $http) {
var result = $http.get("/Contact/PassThisToAngular");
result.success(function (data) {
$scope.customers = data;
});
}
</script>
Controller Side:
public string PassThisToAngular()
{
var customer = new List<MvcApplication1.Models.Customer>()
{
new MvcApplication1.Models.Customer() {Name = "Pauly-D", City = "New
Jersey"},
new MvcApplication1.Models.Customer() {Name = "Snooki", City = "New
Jersey"}
};
var setting = new JsonSerializerSettings{ContractResolver=new
CamelCasePropertyNamesContractResolver()};
return JsonConvert.SerializeObject(customer, Formatting.None, setting);
}
Upvotes: 3
Reputation: 16498
Mvc action
public List<Customer> PassThisToAngular()
{
var customers = new List<Customer>()
{
new Customer() {Name = "Pauly-D", City = "New Jersey"},
new Customer() {Name = "Snooki", City = "New Jersey"}
};
return customers
}
JS:
function SimpleController($scope, $http) {
$scope.customers =[];
$http.get(/[controller name]/PassThisToAngular).then(function(data){
angular.copy(data,$scope.customers )
}, function(){
alert("Can't get data")
});
}
Upvotes: 1