如何将模型数据传递给帖子请求?

时间:2015-08-12 10:41:12

标签: angularjs

如何获取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"/>

3 个答案:

答案 0 :(得分:3)

从范围内阅读:$scope.raw_url

来自documentation

  

ngModel指令使用NgModelController将输入,select,textarea(或自定义表单控件)绑定到作用域上的属性,NgModelController由此指令创建并公开。

答案 1 :(得分:3)

你几乎就在那里,对于每个 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);

但是,我建议将您的帖子请求包含在服务 / 工厂中,这是一种有条理的做事方式。

答案 2 :(得分:1)

此行中的

$http.post('/add', {url: raw_url})会将raw_url替换为$scope.raw_url