简体   繁体   中英

Passing data from MVC model to an Angular Controller

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?

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);
 }]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM