2

I want to be able to pass user input values from a submit button that is fired in a controller to a factory which loads the values, stored as variables, to an $http.get() request. How would I pass this value from the controller to the service? Am I going about this the right way?

controller

'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;
  });
  };
});

factory

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>
3
  • 1
    If you're shooting for and angular approach, you just ditch jQuery and pull from the form/input, that's what ng-model is for. Also, I think your factory is off just a little, does it actually work? Commented Dec 1, 2014 at 21:55
  • Ok, I'll dig deeper into ng-model. I was thinking that as I wrote this. Yes, it works. I have to use $http instead of $resource because of the Base64 encoding that I need to pass. Commented Dec 1, 2014 at 21:59
  • I'm gonna post a more specific answer soon.. working on it Commented Dec 1, 2014 at 22:01

1 Answer 1

1

Your controller doesn't need jQuery, best not to use it at all and learn the angular way.

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);
        });
    };
});

Your factory should probably use take an input and follow a general pattern, here is my version of your factory:

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);
        }
    };

});
Sign up to request clarification or add additional context in comments.

4 Comments

This makes so much more sense to me. The deferred object and .then() method is so much better than using .success and .error. I did originally have a return with a method before but it wasn't working for me. In your code above sendData isn't being used in the controller or service. Where should it be placed? I'm thinking as phoneService.sendData() Also I'm unsure of where the successResponse and failureResponse parameters are being created and if they're really needed. I'm working on this now and I'll update the post once I have it solved or more in depth questions, comments, concerns.
My mistake, it was supposed to use sendData, corrected above in the controller
Thanks a bunch for your help SoluableNonagon. This helped me get over a wall that I had been hitting for a while.
No problem, there are guides out there which have even better examples than this. Ones which use service, factory, and provider in various ways, unfortunately there aren't too many guides which show how to transition from jQuery to Angular

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.