简体   繁体   English

AngularJS和IONIC中的控制器之间共享数据

[英]Sharing Data between Controllers in AngularJS and IONIC

I'm trying to share data via a service that uses the $HTTP function between controllers. 我正在尝试通过在控制器之间使用$ HTTP函数的服务共享数据。 I'm trying to pass the return data in SUCCESS to another controller. 我正在尝试将SUCCESS中的返回数据传递给另一个控制器。 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 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.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);
});

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. 例如,有一个http://lokijs.org/ ,它也声称数据在会话之间保持不变,因为数据也被写入文件中。 And it replaces SQLite . 并且它替代了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. 如果在{{valuetobedisplayedfromcontroller}}类的范围内没有要显示的值,您的html就会变得时髦。

There are 2 options to fix this. 有2个解决方案。 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. 可以在html指令中使用ng-if条件语句,也可以将整个控制器封装在if命令中,该命令检查全局变量以查看数据是否已加载并显示加载屏幕,并防止用户输入和超时返回错误。

I'm very keen to learn if there are other/better solutions. 我非常想知道是否还有其他/更好的解决方案。

you can store received data from API in $rootScope or global var or you can store data in a factory. 您可以将收到的来自API的数据存储在$ rootScope或global var中,也可以将数据存储在工厂中。

example for using $rootScope 使用$ 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);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM