Dwill
Dwill

Reputation: 516

Sharing Data between Controllers in AngularJS and IONIC

I'm trying to share data via a service that uses the $HTTP function between controllers. I'm trying to pass the return data in SUCCESS to another controller. Something is wrong I think in the service the data doesn't get to the second controller. below is my code can someone take a look at it and tell me what I'm doing wrong point me to the right direction on what to do.

services.js

.factory('userService', function ($http) {
    var url = "url.php";
    var headers = {
        'Content-Type' : 'application/x-www-form-urlencoded; charset-UTF-8'
    };
    var params = "";
    return {

        getUsers : function (entry, searchTypReturn) {
            params = {
                entry : entry,
                type : searchTypReturn,
                mySecretCode : 'e8a53543fab6f5e'
            };

            return $http({
                method : 'POST',
                url : 'https://servicemobile.mlgw.org/mobile/phone/phone_json.php',
                headers : {
                    'Content-Type' : 'application/x-www-form-urlencoded; charset-UTF-8'
                },
                transformRequest : function (obj) {
                    var str = [];
                    for (var p in obj)
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    return str.join("&");
                },
                data : params
            })
            .success(function (data, status, headers, config) {

                return data;

            });

        }
    }
})

controller.js

.controller('phoneController', function ($scope, md5, $http, userService, $ionicLoading, $location, $ionicPopup) {

    userService.getUsers(form.entryText, searchTypReturn).success(function (data, status, headers, config) {
        $ionicLoading.hide();
        $scope.name = data.PlaceDetailsResponse.results[0].first_name;
        if ($scope.name == 0) {
            $scope.showAlert();

        } else {

            $location.path('phoneView');
            $ionicLoading.hide();
        }
    }).error(function (data, status, headers, config) {
        $scope.showAlert();
        $ionicLoading.hide();
    })

});

.controller('phoneViewController', function ($scope, userService) {
    $scope.input = userService;
    console.log('This is from phoneView', $scope.input);
});

Upvotes: 0

Views: 129

Answers (2)

tony
tony

Reputation: 11

Nasser's answer is the correct one. There are other ways of keeping track of things in memory if it is just session based.

For example there is http://lokijs.org/ which also claims that the data persist between sessions because it is written to a file as well. And it replaces SQLite.

The relationship between the controllers and the directives which get the data to be displayed from the scope of the directives are loosely coupled.

If there are no values to be displayed in the scope like {{valuetobedisplayedfromcontroller}} your html becomes funky.

There are 2 options to fix this. Either use ng-if conditionals in the html directives or encapsulate the whole controller in an if command which checks a global variable to see if the data is loaded and show a loading screen and prevent user input and return error with a timeout.

I'm very keen to learn if there are other/better solutions.

Upvotes: 1

Nasser Ghiasi
Nasser Ghiasi

Reputation: 372

you can store received data from API in $rootScope or global var or you can store data in a factory.

example for using $rootScope

angularApp.controller('phoneController', function($scope, md5, $http, userService, $rootScope, $ionicLoading, $location, $ionicPopup) {

$rootScope.data = userService.getUsers(form.entryText,searchTypReturn).success(function(data, status, headers, config) {
    $ionicLoading.hide();
    $scope.name = data.PlaceDetailsResponse.results[0].first_name;
    if ($scope.name == 0) {
            $scope.showAlert();

    } else {

        $location.path('phoneView');
        $ionicLoading.hide();
    }
 }).error(function(data, status, headers, config) {
    $scope.showAlert();
    $ionicLoading.hide();
})

}
});

.controller('phoneViewController', function($scope,$rootScope) {
$scope.input = $rootScope.data;
console.log('This is from phoneView',$scope.input);
})

using data factory (Recommended)

angularApp.factory('appDataStorage', function () {
var data_store = [];

return {
    get: function (key) {
        //You could also return specific attribute of the form data instead
        //of the entire data
        if (typeof data_store[key] == 'undefined' || data_store[key].length == 0) {
            return [];
        } else {
            return data_store[key];
        }

    },
    set: function (key, data) {
        //You could also set specific attribute of the form data instead
        if (data_store[key] = data) {
            return true;
        }
    },
    unset: function (key) {
        //To be called when the data stored needs to be discarded
        data_store[key] = {};
    },
    isSet: function (key) {
        if (typeof data_store[key] == 'undefined' || data_store[key].length == 0) {
          return false;
        }else {
            return true;
        }
    }
};
});

  angularApp.controller('phoneController', function($scope, md5, $http, userService, $rootScope, $ionicLoading, $location, $ionicPopup , appDataStorage) {

var data = userService.getUsers(form.entryText,searchTypReturn).success(function(data, status, headers, config) {
    $ionicLoading.hide();
    $scope.name = data.PlaceDetailsResponse.results[0].first_name;
    if ($scope.name == 0) {
            $scope.showAlert();

    } else {

        $location.path('phoneView');
        $ionicLoading.hide();
    }
 }).error(function(data, status, headers, config) {
    $scope.showAlert();
    $ionicLoading.hide();
});

appDataStorage.set('key1',data);

}
});

angularApp.controller('phoneViewController', function($scope,$rootScope,appDataStorage) {
$scope.input = appDataStorage.get('key1');
console.log('This is from phoneView',$scope.input);
})

Upvotes: 0

Related Questions