使用 Angular.js 显示 JsonResult

Displaying JsonResult with Angular.js

我正在熟悉 angular.js,使用 $Http.Get.

从文件中 returning Json 数据似乎很容易

在示例中,我会得到这样的 json 数据

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

    artistControllers.controller('ListController', function ($scope, $http) {
    $http.get('json/jsonAngular.txt').success(function (data) {
    $scope.artists = data;
  });
});

我如何获得 Json 结果并将其分配给我的 $scope.artists 例如。

    [HttpPost]
    public JsonResult GetArtists()
    {
        ViewModel model = new ViewModel();
        model.GetArtists();
        return Json(new
        {
            Artists = model.Artists
        });
    }

以我的 class 为例

 public class Artist
{
    public string Initial { get; set; }
    public string Surname { get; set; }
}

是否有一个工作示例,说明我可以在哪里 return 一个 Json 结果并将其呈现在我的 html.

它将像:

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

artistsApp.controller('ListController', function ($scope, $http) {
    $http.get('api/getartists').success(function (data) {
         $scope.artists = data.artists;
    });
});

<ul>
  <li ng-repeat="artist in artists">{{ artist.Surname }}</li>
</ul>

如果 json/jsonAngular.txt 返回您的 json,那么您的其余代码就是代码。您可以像上面那样简单地在 ng-repeat 中访问它。

另请记住,您需要将视图关联到控制器。这通常在您的 app.js 配置部分完成。

$routeProvider
            .when('/', {
                controller: 'artistControllers',
                templateUrl: 'artists.html'
            })

注意:最佳做法是将控制器中的数据访问抽象到服务中,这样您就可以重用数据访问调用。

而不是 $scope.artists = data; 你想要 $scope.artists = data.artists;