【问题标题】:How do I pass model data to a post request?如何将模型数据传递给发布请求?
【发布时间】:2015-08-12 10:41:12
【问题描述】:

如何获取 ng-model 的值并将其放入控制器发布请求中?

    (function(angular) {
    angular.module('urlShortener', ['ngAnimate'])
        .controller('shortenerController', function($scope, $http){
            $scope.customMode = false;
            $scope.passData = function passData(){
                $http.post('/add', {url: raw_url})
                    .success(function(data, status, headers, config) {
                        // this callback will be called asynchronously
                        // when the response is available
                    })
                    .error(function(data, status, headers, config) {
                        // called asynchronously if an error occurs
                        // or server returns response with an error status.
                    });
            }
        })


})(window.angular);

我正在使用的模型:

<input ng-model="raw_url" type="text" placeholder="Paste your url here and we will shrink it!" class="form-control"/>

【问题讨论】:

标签: angularjs


【解决方案1】:

从范围读取它:$scope.raw_url

来自documentation

ngModel 指令使用 NgModelController 将输入、选择、文本区域(或自定义表单控件)绑定到范围上的属性,该属性由该指令创建和公开。

【讨论】:

    【解决方案2】:

    您快到了,对于每个 ng-model,控制器中必须有一个绑定,在您的情况下似乎缺少该绑定。您可以通过以下方式进行:

    (function(angular) {
        angular.module('urlShortener', ['ngAnimate'])
            .controller('shortenerController', function($scope, $http){
                $scope.raw_url; //the binding
                $scope.customMode = false;
                $scope.passData = function passData(){
                    $http.post('/add', {url: $scope.raw_url}) //raw_url to $scope.raw_url
                        .success(function(data, status, headers, config) {
                            // this callback will be called asynchronously
                            // when the response is available
                        })
                        .error(function(data, status, headers, config) {
                            // called asynchronously if an error occurs
                            // or server returns response with an error status.
                        });
                }
            })
    
    
    })(window.angular);
    

    但是,我建议将您的发布请求包装在 service/factory 中,这是一种有角度的做事方式。

    【讨论】:

    • 从未使用过 $resource。你有什么建议?
    • $resource 是位于 $http 之上的抽象层,采用 RESTful/CRUD 模式。
    • 好的,去看看。到目前为止,我一直在使用带有 promise 的 $http。
    【解决方案3】:

    此行中的$http.post('/add', {url: raw_url})raw_url 替换为$scope.raw_url

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多