簡體   English   中英

AngularJS和IONIC中的控制器之間共享數據

[英]Sharing Data between Controllers in AngularJS and IONIC

我正在嘗試通過在控制器之間使用$ HTTP函數的服務共享數據。 我正在嘗試將SUCCESS中的返回數據傳遞給另一個控制器。 我認為服務中的數據無法到達第二個控制器是有問題的。 下面是我的代碼,有人可以看一下,然后告訴我我做錯了什么,將我指向正確的操作方向。

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

納賽爾的答案是正確的。 如果只是基於會話,還有其他方法可以跟蹤內存中的內容。

例如,有一個http://lokijs.org/ ,它也聲稱數據在會話之間保持不變,因為數據也被寫入文件中。 並且它替代了SQLite

控制器與從指令范圍獲取要顯示數據的指令之間的關系是松散耦合的。

如果在{{valuetobedisplayedfromcontroller}}類的范圍內沒有要顯示的值,您的html就會變得時髦。

有2個解決方案。 可以在html指令中使用ng-if條件語句,也可以將整個控制器封裝在if命令中,該命令檢查全局變量以查看數據是否已加載並顯示加載屏幕,並防止用戶輸入和超時返回錯誤。

我非常想知道是否還有其他/更好的解決方案。

您可以將收到的來自API的數據存儲在$ rootScope或global var中,也可以將數據存儲在工廠中。

使用$ 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);
})

使用數據工廠(推薦)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM