在Asp.netMVC中使用AngularJS循环json数据
本文关键字:AngularJS 循环 json 数据 Asp netMVC | 更新日期: 2023-09-27 17:58:19
我正在尝试通过ajax获取记录,并使用AngularJS进行显示。但是我的代码甚至没有调用控制器操作。
我正在尝试这个代码。。
<div ng-controller="MyCtrl">
<div ng-repeat="result in products">
{{result.ProductName}}
</div>
</div>
Ajax:
function MyCtrl($scope) {
$.ajax({
url: "/Products/Get/",
type: "POST",
success: function (data) {
// Success message
var myApp = angular.module('myApp', []);
$scope.products = data;
},
error: function () {
// Fail message
},
});
}
我用这篇文章是为了让它发挥作用。
您的方法是错误的。您应该使用angularJS的控制器指令来调用服务来使用json数据。
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('MyCtrl', function ($scope, $http) {
$http.get('/Products/Get/').success(function (data) {
$scope.products = data;
});
});
</script>
几天前我写了一篇关于这个问题的文章。你可以从这里过去。这可能会有所帮助。
您需要在angularjs中声明module
名称,不要忘记在body或html标记中添加模块名称。。像这样<body data-ng-app="app">
,然后像这样尝试:
<script>
var app = angular.module('app',[]);
app.controller('MyCtrl',function($scope,$http){
bindData();
function bindData(
// it will be nice, if this code your separate to file service...
$http.get('/Products/Get').success(function (callBack) {
$scope.products = callBack.data;
});
);
});
</script>
最佳实现方式:
// in controller, injected you service name like this..
app.controller('MyCtrl',function($scope,$http ,myServices){
bindData();
function bindData(
var promiseGet = myServices.GetAll();
promiseGet.then(function(callBack){ // success
$scope.products = callBack.data;
}
,function(error){ // error
console.log(error);
});
);
});
app.service('myServices',function($http){
var vm = this;
vm.GetAll = function(){
return $http.get('/Products/Get');
}
});
如果您想在ajax函数中获取数据,请键入非POST
。。