2

I have an angular controller inside a mvc view. I need to pass data coming from the MVC model into the angular controller. Currently a developer is using ngInit directive to pass this data.

In xxx.cshtml

<div ng-controller="AssessmentController" ng-init   ="Init('@Model.Status','@Model.ARN','@Model.AssessmentID','@Model.AssessorID',@Model.Contents, @Model.Date_of_Assessment.ToJsonTicks(),'@Model.HouseReferenceID',@Newtonsoft.Json.JsonConvert.SerializeObject(Model.House))">

I pointed out that according to Angular documentation ngInit directive is not to be used to to initialize controllers. https://docs.angularjs.org/api/ng/directive/ngInit

Instead what I suggested was to send the ID in ngInit directive and

<div ng-controller="AssessmentController" ng-init   ="Init('@Model.AssessmentID'">

Then after that use $http [https://docs.angularjs.org/api/ng/service/$http] service to get the remainder of data from the Angular controller.

The developer is refusing my idea saying it's faster to just send all the data through ngInit directive instead of having to do another call to get the data inti the Angular controller.

What do you guys think about this scenario? The only point I have right now is that this code is FUGLY and it not according to standards. How would you convince a developer to follow the path I suggested. Or am I completely wrong here?

If you had to pass data from the MVC model into the Angular controller how would you do it?

Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
Kumudu
  • 136
  • 1
  • 5
  • I like the selected answer for this : http://stackoverflow.com/questions/22039198/how-can-i-pass-model-to-angular-ng-init – Jason Evans Aug 28 '14 at 08:18
  • 1
    I would go for the $http service. I do have a similar case and use the exact same approach. I do not know if it is a good approach, but i wouldn't like passing a million params in an init function. – Giannis Paraskevopoulos Aug 28 '14 at 08:19
  • This is exactly my view but when explaining this to the junior developer all I could come up with was that this is not according to standards and this looks FUGLY. I don't think I got through to him. How would you have explained it? – Kumudu Aug 28 '14 at 09:07
  • Anyone else has any other input on this? – Kumudu Aug 29 '14 at 21:07

1 Answers1

0

There is sample how i do it in Razor MVC

MVC View Code

<div ng-controller='myController'>
    <input type="hidden" id="companyId" value="@Model.CompanyId"/>
 </div>

Angular controller code, logging to console companyId value from the view

 app.Controller("myController",['$scope',function($scope){
        console.log(document.getElementById('companyId').value);
 }]);
Marat Batalandabad
  • 930
  • 13
  • 15