获取MVC模型数据并将其传递给AngularJS控制器 [英] Getting and passing MVC Model data to AngularJS controller

查看:88
本文介绍了获取MVC模型数据并将其传递给AngularJS控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对AngularJS很陌生,我在这里不知所措。

I'm pretty new to AngularJS and I'm at a loss here.

现在我的MVC程序使用Razor显示我的.mdf中的所有数据数据库(即: @ Html.DisplayFor(modelItem => item.LastName))。但是,我想主要是Angular。我正在尝试使用ng-repeat来显示所有Model数据,但我不确定如何将该Model数据传递给Angular控制器然后使用它。我已经尝试在我的ng-init中将Model序列化为JSON,但我认为我做得不对(显然)。

Right now my MVC program uses Razor to display all the data in my .mdf database (i.e: @Html.DisplayFor(modelItem => item.LastName) ). However, I want to go mostly Angular. I am trying to use ng-repeat to display all of the Model data, but I am not sure how to pass that Model data to the Angular controller and then use it. I have tried serializing the Model to JSON in my ng-init, but I don't think I'm doing it right (obviously).

这是我的代码:

// controller-test.js

var myApp = angular.module('myModule', []);

myApp.controller('myController', function ($scope) {
    $scope.init = function (firstname) {
        $scope.firstname = firstname;
    }
});

<!-- Index.cshtml -->

@model IEnumerable<Test.Models.Employee>

@{
    ViewBag.Title = "Index";
}

<div ng-app="myModule">
    <div ng-controller="myController" ng-init="init(@Newtonsoft.Json.JsonConvert.SerializeObject(Model))">
         <table>
             <tr ng-repeat= <!--THIS IS WHERE I'M STUCK -->
         </table>
    </div>
</div>

<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/controller-test.js"></script>
@Scripts.Render("~/Scripts/angular.js")

我不确定我应该重复从序列化模型中获取FirstName。我觉得我有所有的部分,但只是不确定如何连接它们。

I'm not sure exactly what I should be repeating on to get the FirstName from the serialized Model. I feel like I have all the pieces, but just unsure how to connect them.

推荐答案

如果你有钥匙<$ c您的Json对象上的$ c> firstName 如:

{
 "employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter","lastName":"Jones"}
  ]
}

您可以通过以下方式完成。

You can do it in the following way.

在您的控制器上:

myApp.controller('myController', function ($scope) {
    $scope.init = function (employees) {
        $scope.employees = employees;
    }
});

在您的观点中:

<table>
    <tr ng-repeat= "employee in employees">
        <td>{{ employee.firstName }}<td>
    </tr>
</table>

这篇关于获取MVC模型数据并将其传递给AngularJS控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆