在控制器中将数据添加到Angular表单(Add data to Angular form in controller)

编程入门 行业动态 更新时间:2024-10-27 03:31:13
在控制器中将数据添加到Angular表单(Add data to Angular form in controller)

我是Angular的新手,我正试图让它使用我的API从表单创建一个新的Droplet。 我可以让它正确提交我的表单数据,但我需要为用户ID添加一个隐藏字段。 我假设最好的方法是在将它发送到我的工厂之前在控制器中添加它作为POST请求发送。 我的控制器看起来像这样:

$scope.createNewDroplet = function () { drop.create($scope.drop).success(function(droplet) { $scope.createdDroplet = droplet; }); };

工厂看起来像这样:

app.factory('drop', ['$http', function($http) { return { create: function (drop) { return $http.post('/droplets/', drop) } } }]);

我可以通过$ scope.user.id访问用户ID。 我如何将“user_id:$ scope.user.id”添加到请求中?

I am new to Angular and am trying to get it to create a new Droplet from a form using my API. I can get it to submit my form data correctly but I need to add a hidden field for a user ID. I assume the best way is to add this in the controller before sending it to my factory to be sent as POST request. My controller looks like this:

$scope.createNewDroplet = function () { drop.create($scope.drop).success(function(droplet) { $scope.createdDroplet = droplet; }); };

And the factory looks like this:

app.factory('drop', ['$http', function($http) { return { create: function (drop) { return $http.post('/droplets/', drop) } } }]);

I have access to the user id through $scope.user.id. How would I go about adding "user_id: $scope.user.id" to the request?

最满意答案

尝试这个...

$http.post('/droplets/', {drop: drop, userId: $scope.user.id})

编辑

回答你关于无法在工厂中访问范围的评论......

在调用工厂代码之前更改控制器中的数据。

$scope.createNewDroplet = function () { $scope.drop.user_id = $scope.user.id; drop.create($scope.drop).success(function(droplet) { $scope.createdDroplet = droplet; }); };

Try this...

$http.post('/droplets/', {drop: drop, userId: $scope.user.id})

Edit

In answer to your comment about not being able to access scope in the factory...

Change the data in your controller before calling your factory code.

$scope.createNewDroplet = function () { $scope.drop.user_id = $scope.user.id; drop.create($scope.drop).success(function(droplet) { $scope.createdDroplet = droplet; }); };

更多推荐

$scope,user,ID,添加,电脑培训,计算机培训,IT培训"/> <meta name="description

本文发布于:2023-07-22 10:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   中将   控制器   数据   form

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!