gpt4 book ai didi

javascript - 使用 Angular.js 显示 JsonResult

转载 作者:行者123 更新时间:2023-11-28 15:29:42 26 4
gpt4 key购买 nike

我正在熟悉 angular.js,并且使用 $Http.Get 从文件返回 Json 数据似乎非常容易。

在一个例子中,我会像这样获取我的 json 数据

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

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

例如,我如何获取 JsonResult 并将其分配给我的 $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; }
}

是否有一个可行的示例,我可以在其中返回 JsonResult 并将其呈现在我的 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 中简单地访问它。

还请记住,您需要将 View 与 Controller 关联起来。这通常在您的 app.js 配置部分中完成。

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

注意:最佳实践是将数据访问从 Controller 中抽象到服务中,以便您可以重用数据访问调用。

关于javascript - 使用 Angular.js 显示 JsonResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27823283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com