将数据从输入字段传递到角度工厂中的$ http.get

时间:2014-12-01 21:53:58

标签: javascript angularjs

我希望能够将用户输入值从控制器中触发的提交按钮传递到工厂,该工厂将存储为变量的值加载到$ http.get()请求。如何将此值从控制器传递给服务?我是以正确的方式来做这件事吗?

控制器

'use strict';
angular.module('myApp')
.controller('phoneSubmitController', function($http, phoneService) {
 $scope.submitPhone = function(data) {
  phoneService.then(function(data) {
    var phone  = $('#phone_number').val();
    var phone1 = phone.substring(1,4);
    var phone2 = phone.substring(5,8);
    var phone3 = phone.substring(9,13);
    $scope.JAWN = data;
  });
  };
});

工厂

angular.module('myApp')
.factory('phoneService', function($http) {
var promise = $http.get('http://dev.website.com:8080/api/get?areacode=' + phone1 + '&exchange=' + phone2 + '&lastdigits' + phone3, {
  headers: {
    'Authorization': "Basic " + Base64.encode("Allen" + ":" + "Iverson1"),
    'Content-Type': 'application/json'
  },
  contentType: 'application/json',
  data: angular.toJson(JAWN),
  cache: false
})
.success(function(data) {
  console.log('success = ' + this);
  JAWN = data;
})
.error(function($log) {
  console.log($log);
});
return promise;
});

HTML

<div id="phone-wrapper">
    <h4>Enter a phone number:</h4>
    <label for="phone_number">
      <input type="text" id="phone_number" ng-model="data.phone" ui-mask="(***)***-****" placeholder="(___)___-____"/>
    </label>
    <div class="row"></div>
    <button class="btn btn-lg btn-primary scrollTop" type="submit" id="submitPhone" value="Submit" ng-disabled="phoneForm.$invalid">Start</button>
    <br/>
  </div>

1 个答案:

答案 0 :(得分:1)

您的控制器不需要jQuery,最好不要使用它并学习角度方式。

HTML:

<input type="text" id="phone_number" ng-model="myInput.phone" ui-mask="(***)***-****" placeholder="(___)___-____"/>

// inject $scope into controller, otherwise your ng-model is useless in your html
.controller('phoneSubmitController', function($scope, $http, phoneService) {

    $scope.myInput = {
        phone: ""
    };
    $scope.submitPhone = function() { // no need to pass anything into here

        // your phone service should take an input param, right? and send that number out?
        phoneService.sendData($scope.myInput.phone).then(function(successResponse) {
            console.log(successResponse);
        }, function(failureResponse){
            console.log(failureResponse);
        });
    };
});

您的工厂应该使用输入并遵循一般模式,这是我的工厂版本:

angular.module('myApp').factory('phoneService', function($http, $q) { // inject $ as well for use of promises
    var JAWN = null;
    // the factory is a singleton which is reusable, it can be called any time to send data, given an input
    return {
        sendData: function(phoneNumber){
            var deferred = $q.defer(); // create a deferred object (think promise, this will either fail or succeed at some point)

            var phone1 = phoneNumber.substring(1,4);
            var phone2 = phoneNumber.substring(5,8);
            var phone3 = phoneNumber.substring(9,13);

            $http.get('http://dev.website.com:8080/api/get?areacode=' + phone1 + '&exchange=' + phone2 + '&lastdigits' + phone3, {
                headers: {
                    'Authorization': "Basic " + Base64.encode("Allen" + ":" + "Iverson1"),
                    'Content-Type': 'application/json'
                },
                contentType: 'application/json',
                data: angular.toJson(JAWN),
                cache: false
            })
            // handle some success/error here, like logging, and if needed in your controller as well
            .then(function(successResponse){ // handle success in factory
                console.log('success', successResponse);
                deferred.resolve(successResponse); // mark it as successful
                JAWN = data; 

            }, function(errorResponse){ // handle failure in factory
                console.log('failure', errorResponse);
                deferred.reject(errorResponse); // mark it as failed
            });

            return deferred.promise; // return a promise

        }, someOtherFunction: function(someData){
               // use some other http call as phoneService.someOtherFunction(some Input Data);
               return $http.get('someOtherURL', someData);
        }
    };

});