3

Currently, my viewModel is passed from my controller to my view and it is populated list. I Can reference my Model in my view currently like Model.

However, if I wanted to do something like this:

<table style="margin-top:20px" cellpadding="2" cellspacing="2" border="1">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
        <tr ng-show="users != null" ng-repeat="user in users">
            <td>{{user.FirstName}}</td>
            <td>{{user.LastName}}</td>
        </tr>

    </table>

users is not defined or recognized when I debug my view although "Model" is and it has the correct values I"m looking for. I'm familiar with razor syntax and getting the model or checking the model through Razor but what if I wanted to do a foreach loop above but with ng-repeat. How do I make sure I have the correct Model reference from my controller?

where Users is the model I'm getting the data from that's being persisted.

Kala J
  • 2,040
  • 4
  • 45
  • 85

1 Answers1

1

Razor is executed on the server and angular is on client side. So you cannot simply acccess your server side model in your client side code.

What you can do is, in your razor view, serialize the model and create a json representation of the data and inject this object to your angular controller using the value provider.

So in your razor view,

@model YourViewModel
<div ng-app="app" ng-controller="ctrl as vm">
    <table style="margin-top:20px" cellpadding="2" cellspacing="2" border="1">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
        <tr ng-show="vm.users != null" ng-repeat="user in vm.users">
            <td>{{user.Name}}</td>
            <td>{{user.Name}}</td>
        </tr>    
    </table>
</div>
@section Scripts{   
  <script src="~/Scripts/YourAngularController.js"></script>    
  <script>
    var m = angular.module("app")
         .value("pageModel",@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));

  </script>    
}

And in your angular controller which is in YourAngularController.js file,

var app = angular.module("app", []);
var ctrl = function (pageModel) {

    var vm = this;
    vm.users = pageModel; //assuming pageModel is a list of users

};
app.controller("ctrl", ctrl);
Shyju
  • 214,206
  • 104
  • 411
  • 497