AngularJS不能调用MVC控制器
问题描述:
我是新的angularJS,即时尝试调用我的MVC jsonresult获取数据,因此填充列表,但我的GetLogs函数不会去MVC jsonresult/misc/getlogs(我也有完整的URL tryed)。代码是:AngularJS不能调用MVC控制器
<body ng-app="Log">
<div ng-controller="MiscController">
<ul ng-repeat="log in logs" class="notification-body">
<li>
<span class="unread">
<a href="javascript:void(0);" class="msg">
<img src="/content/img/avatars/4.png" alt="" class="air air-top-left margin-top-5" width="40" height="40" />
<span class="from">John Doe <i class="icon-paperclip"></i></span>
<time>2 minutes ago</time>
<span class="subject">{{log.Name}}</span>
<span class="msg-body">Hello again and thanks for being a part of the newsletter. </span>
</a>
</span>
</li>
</ul>
</div>
<script type="text/javascript">
$(document).ready(function() {
GetLogs();
});
function GetLogs() {
var app = angular.module("Log", []);
app.controller('MiscController', function ($scope, $http) {
$http.post("/misc/getlogs")
.success(function (data) { $scope.logs = data.logs; });
});
}
</script>
答
你不应该调用getLogs()函数document.ready
角ng-app
将首先运行,并要求该模块将抛出和模块错误。
所以解决方案是在页面加载时创建一个角度模块。
<script type="text/javascript">
var app = angular.module("Log", []);
app.controller('MiscController', function ($scope, $http) {
$http.post("/misc/getlogs")
.success(function (data) { $scope.logs = data.logs; });
});
</script>
更新
如果你想负荷角度在页面上懒洋洋地那么就使用angular.bootstrap
将初始化元件上的角度默默。移动这种方法之前,你需要从你页面删除ng-app
指令。
<script type="text/javascript">
$(document).ready(function() {
GetLogs();
});
function GetLogs() {
var app = angular.module("Log", []);
app.controller('MiscController', function ($scope, $http) {
$http.post("/misc/getlogs")
.success(function (data) { $scope.logs = data.logs; });
});
angular.bootstrap(document.body, ['Log'])
}
</script>
哦,谢谢我使用了该函数,因为我需要从一个按钮(用于刷新)调用它。无论如何,我无法达到我的jsonresult(或的ActionResult)不明白为什么 – Sauron
@Sauron我认为,如果你是从你的方法返回的JSON应该有'JSONBehaviour.AllowGet'&应该使用'$ http.get'而不是' POST' .. –
你的“更新”的工作完美!最后,我可以达到jsonresult :)感谢的人 – Sauron