Search code examples
angularjsparameterscontrollerfactories

Is my Angular controller well defined for the way I included the factory ?


I am using a factory in my in my todoController . I am not sure if the $scope parameter and factory parameter are written the right way as my controller method are not working anymore.

Is this the right way ?

Here is my controller:

facebookExample.controller('todoController', ['$scope', function($scope,   PaypalService) {
// Initialize the todo list array
//if local storage is null save the todolist to local storage
$scope.todoList = [];
$scope.DoRequested = [];
scope.FundingProcess = [];

if (localStorage.getItem("mytodos") === null)
{
localStorage.setItem("mytodos", angular.toJson($scope.todoList));
}else
{
//set the todolist from local storage
$scope.todoList = angular.fromJson(localStorage.getItem("mytodos"));
}

// Add an item function
$scope.todoAdd = function(){

//check to see if text has been entered, if not exit
if ($scope.todoInput === null || $scope.todoInput === ''){ return; }

//if there is text add it to the array
$scope.todoList.push({todoText:$scope.todoInput, 
  todoAdmin:'' , doRequested: '', beingFunded: '', 
   adminAprovedRequest:false, currentFund: 0, userAproved: false, user_email:'' , userdidWork: "false", adminCheckedWork: "false",
     done:false});

//clear the textbox
$scope.todoInput = "";

//resave the list to localstorage
localStorage.setItem("mytodos", angular.toJson($scope.todoList));
};
//Do button
$scope.do = function(x){
$scope.DoRequested.push(x);
// Send email notifier to admin 
/*
$.ajax({
type: “POST”,
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
‘key’: ‘n3ZIdxXIRIZbvUWw6Z34wA’,
‘message’: {
  ‘from_email’: ‘[email protected]’,
  ‘to’: [
      {
        ‘email’: ‘[email protected]’,
        ‘name’: ‘RECIPIENT NAME (OPTIONAL)’,
        ‘type’: ‘to’
      },
      {
        ‘email’: ‘[email protected]’,
        ‘name’: ‘ANOTHER RECIPIENT NAME (OPTIONAL)’,
        ‘type’: ‘to’
      }
    ],
  ‘autotext’: ‘true’,
  ‘subject’: ‘NEW TASK ASSIGNMENT REQUEST!’,
  ‘html’: ‘<div!’
}
}
}).done(function(response) {
console.log(response); // if you're into that sorta thing
});
*/
};
$scope.fund = function(x){
//$scope.FundingProcess.push(x);
PaypalService.initPaymentUI().then(

   function(){
       PaypalService.makePayment($scope.donationAmount, "Task Funding").then(
           function(data){
               if(data.response.state === "approved"){
                   alert("Successful transaction !");
               }

               else{
                   alert("Error !");
               }
           }

           );
   }     
   );  
};

$scope.remove = function() {
//copy list
var oldList = $scope.todoList;
//clear list
$scope.todoList = [];
//cycle through list
angular.forEach(oldList, function(x) {
  //add any non-done items to todo list
    if (!x.done) $scope.todoList.push(x);
});
//update local storage
 localStorage.setItem("mytodos", angular.toJson($scope.todoList));
};
//The Update function
//This waits 100ms to store the data in local storage
$scope.update = function() {
//update local storage 100 ms after the checkbox is clicked to allow it to process
setTimeout(function(){
localStorage.setItem("mytodos", angular.toJson($scope.todoList));
},100);
};
}]);

And here is my factory:

facebookExample.factory('PaypalService', ['$q', '$ionicPlatform', 'shopSettings', '$filter', '$timeout', function ($q, $ionicPlatform, shopSettings, $filter, $timeout) {



    var init_defer;
    /**
     * Service object
     * @type object
     */
    var service = {
        initPaymentUI: initPaymentUI,
        createPayment: createPayment,
        configuration: configuration,
        onPayPalMobileInit: onPayPalMobileInit,
        makePayment: makePayment
    };


    /**
     * @ngdoc method
     * @name initPaymentUI
     * @methodOf app.PaypalService
     * @description
     * Inits the payapl ui with certain envs. 
     *
     * 
     * @returns {object} Promise paypal ui init done
     */
    function initPaymentUI() {

        init_defer = $q.defer();
        $ionicPlatform.ready().then(function () {

            var clientIDs = {
                "PayPalEnvironmentProduction": shopSettings.payPalProductionId,
                "PayPalEnvironmentSandbox": shopSettings.payPalSandboxId
            };
            PayPalMobile.init(clientIDs, onPayPalMobileInit);
        });

        return init_defer.promise;

    }


    /**
     * @ngdoc method
     * @name createPayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Creates a paypal payment object 
     *
     * 
     * @returns {object} PayPalPaymentObject
     */
    function createPayment(total, name) {

        // "Sale  == >  immediate payment
        // "Auth" for payment authorization only, to be captured separately at a later time.
        // "Order" for taking an order, with authorization and capture to be done separately at a later time.
        var payment = new PayPalPayment("" + total, "EUR", "" + name, "Sale");
        return payment;
    }
    /**
     * @ngdoc method
     * @name configuration
     * @methodOf app.PaypalService
     * @description
     * Helper to create a paypal configuration object
     *
     * 
     * @returns {object} PayPal configuration
     */
    function configuration() {
        // for more options see `paypal-mobile-js-helper.js`
        var config = new PayPalConfiguration({merchantName: shopSettings.payPalShopName, merchantPrivacyPolicyURL: shopSettings.payPalMerchantPrivacyPolicyURL, merchantUserAgreementURL: shopSettings.payPalMerchantUserAgreementURL});
        return config;
    }

    function onPayPalMobileInit() {
        $ionicPlatform.ready().then(function () {
            // must be called
            // use PayPalEnvironmentNoNetwork mode to get look and feel of the flow
            PayPalMobile.prepareToRender(shopSettings.payPalEnv, configuration(), function () {

                $timeout(function () {
                    init_defer.resolve();
                });

            });
        });
    }

    /**
     * @ngdoc method
     * @name makePayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Performs a paypal single payment 
     *
     * 
     * @returns {object} Promise gets resolved on successful payment, rejected on error 
     */
    function makePayment(total, name) {


        var defer = $q.defer();
        total = $filter('number')(total, 2);
        $ionicPlatform.ready().then(function () {
            PayPalMobile.renderSinglePaymentUI(createPayment(total, name), function (result) {
                $timeout(function () {
                    defer.resolve(result);
                });
            }, function (error) {
                $timeout(function () {
                    defer.reject(error);
                });
            });
        });

        return defer.promise;
    }

    return service;
}]);

 //To use this service 
/**
 PaypalService.initPaymentUI().then(function () {
                PaypalService.makePayment($scope.total(), "Total").then(...)
 });
 ***/




 // shop settings
 // include appConstant into your app.js 
 angular.module('appConstant', []).constant('shopSettings',{    
 payPalSandboxId : 'APP-80W284485P519543T',
 payPalProductionId : 'production id here',
 payPalEnv: 'PayPalEnvironmentSandbox',   // for testing  production for production
 payPalShopName : 'You-Serve',
 payPalMerchantPrivacyPolicyURL : 'http://you-serve.org',
 payPalMerchantUserAgreementURL : 'http://you-serve.org'

 });

Solution

  • Didn't read through all but the controller needs to be defined like this....

    facebookExample.controller('todoController', ['$scope','PaypalService', 
        function($scope, PaypalService) {
        //code to be executed.
    }]);
    

    This way if you minify your code Angular knows that its expecting the strings $scope and PaypalService within the definition of the controller. You can read more about defining controllers and injecting services at the following links.

    Controllers

    https://docs.angularjs.org/guide/controller

    Services

    https://docs.angularjs.org/guide/services

    Dependency Injection

    https://docs.angularjs.org/guide/di