我有这个代码在Angular中创建一个待办事项列表。
<div class="row" ng-app="ToDo">
<div ng-controller="todocontroller">
<button ng-click="save()">Save</button>
<br />
<form name="frm" ng-submit="addTodo()">
<input type="text" name="newTodo" ng-model="newTodo" required />
<button ng-disabled="frm.$invalid">Go</button>
</form>
<button ng-click="clearCompleted()">ClearCompleted</button>
<ul>
<li id="test" ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done"/>
<span ng-class="{'done':todo.done}">
{{todo.title}}
</span>
</li>
</ul>
</div>
</div>
代码工作正常并按原样创建项目列表。我现在希望能够将列表传递给我的方法:
public ActionResult SaveListFromAngular()
{
//Do stuff
return View();
}
我不知道如何在Angular中执行此操作。我是否应该以某种方式遍历列表? 我有兴趣在Angular中学习正确的方法,这对我来说是一个新的框架。
$scope.save = function () {
//Pass list to
//Home/SaveListFromAngular
}
帮助表示感谢! 感谢
编辑: 我的完整脚本,建议在底部添加:
angular.module('ToDo', []).
controller('todocontroller', [
'$scope', function($scope) {
$scope.todos = [
{ 'title': 'build todo app', 'done': false }
];
$scope.addTodo = function() {
$scope.todos.push({ 'title': $scope.newTodo, 'done': false });
$scope.newTodo = "";
}
$scope.clearCompleted = function() {
$scope.todos = $scope.todos.filter(function(item) {
return !item.done;
});
}
}
]);
function todocontroller($scope, $http) {
$scope.save = function () {
alert("fgfg");
$http({
method: 'POST',
url: '/Home/SaveListFromAngular',
headers: {
"Content-Type": "application/json"
},
data: { todos: $scope.todos }
});
}
}
答案 0 :(得分:1)
angular.module('ToDo', []).
controller('todocontroller', [
'$scope', "$http", function($scope, $http) {
$scope.todos = [
{ 'title': 'build todo app', 'done': false }
];
$scope.save = function (){
$http({
method: 'POST',
url: '/someUrl',
headers: {
"Content-Type": "application/json"
},
data: { todos: $scope.todos }
});
}
$scope.addTodo = function() {
$scope.todos.push({ 'title': $scope.newTodo, 'done': false });
$scope.newTodo = "";
}
$scope.clearCompleted = function() {
$scope.todos = $scope.todos.filter(function(item) {
return !item.done;
});
}
}
]);
在你的行动中
[HttpPost]
public ActionResult SaveListFromAngular(List<Todo> todos)
{
return View();
}
public class Todo
{
public string Title { get; set; }
public bool Done { get; set; }
}
答案 1 :(得分:1)
我的建议是您设置Web Api并使用Angular以及此REST服务层。
有了这个说,你需要做的就是发布像:
这样的字段 $http.post('api/Todo',{ /*object or list*/}).success(function(response) {
console.log("success");
}).error(function(err){
console.log("failure")
});