Accentuation problem in array generation with Angularjs

Asked

Viewed 398 times

0

I’m having trouble printing the user’s payment methods, they are being stored in my Localstorage with wrong accentuation:

inserir a descrição da imagem aqui

// PEGA $scope.formaspag (array2 no localstorage) E COMPARA COM OS CÓDIGOS DE FORNECEDORES_CONFIGURA_FRETE E IMPRIME NA TELA

        $scope.array1 = window.localStorage.getItem("tipos_pagamentos");

        $scope.array1 = $scope.array1.split(',');

        console.log($scope.array1);

I will post the complete codes below:

My controller:

    (function () {
    "use strict";

    angular.module("nhaac").controller("formaPagCtrl", function ($scope, $rootScope, $state, $ionicScrollDelegate, $http, $httpParamSerializer, $stateParams, $timeout, $ionicLoading, $ionicPopup, $ionicPopover, $ionicSlideBoxDelegate, $ionicHistory, ionicMaterialInk, ionicMaterialMotion, $ionicModal, sharedCartService, sharedFilterService, $cordovaOauth, $location, $cordovaDialogs) {

        $rootScope.page_id = "forma_pag";

        $scope.scrollTop = function () {
            $ionicScrollDelegate.$getByHandle("top").scrollTop();
        };
        // open external browser 
        $scope.openURL = function ($url) {
            window.open($url, "_system", "location=yes");
        };
        // open AppBrowser
        $scope.openAppBrowser = function ($url) {
            window.open($url, "_blank", "closebuttoncaption=Done");
        };
        // open WebView
        $scope.openWebView = function ($url) {
            window.open($url, "_self");
        };

        // Set Motion
        $timeout(function () {
            ionicMaterialMotion.slideUp({
                selector: ".slide-up"
            });
        }, 300);


        $scope.email = window.localStorage.getItem("email");
        $scope.name = window.localStorage.getItem("name");
        $scope.cidade = window.localStorage.getItem("cidade");
        $scope.estado = window.localStorage.getItem("estado");
        $scope.cod_cliente = window.localStorage.getItem("cod_cliente");

        $scope.total_pedido_tmp = window.localStorage.getItem("total_pedido");
        $scope.troco_tmp = window.localStorage.getItem("frete");

        var soma = parseInt($scope.total_pedido_tmp) + parseInt($scope.troco_tmp);

        window.localStorage.setItem("valor_troco_tela_troco", soma);


        $scope.teste = "teste";



        // INICIO LEITURA DE FORMAS DE PAGAMENTO

        // OUTRA COISA PRA ARRAY 2

        var targetQuery = ""; //default param
        var raplaceWithQuery = "";
        // TODO: Dinamics Promoções
        targetQuery = "json=promocao"; //default param
        raplaceWithQuery = "json=promocao";


        var fetch_per_scroll = 1;
        // animation loading 
        $ionicLoading.show({
            template: '<div class="loader"><svg class="circular"><circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/></svg></div>'
        });


        $scope.noMoreItemsAvailable = false; //readmore status
        var lastPush = 0;
        var array2 = [];

        if (window.localStorage.getItem("array2") !== "undefined") {
            array2 = JSON.parse(window.localStorage.getItem("array2"));
            if (array2 !== null) {
                $scope.formaspag = [];
                for (lastPush = 0; lastPush < 10; lastPush++) {
                    if (angular.isObject(array2[lastPush])) {
                        $scope.formaspag.push(array2[lastPush]);
                    };
                }
                $timeout(function () {
                    $ionicLoading.hide();
                }, 500);
            }
        }
        if (!angular.isObject(array2)) {
            $timeout(function () {
                // retry retrieving data
                $http.get("http://vovocooks.com.br/admin/apis/api_listagem/lista_pagamentos.php?json=promocao".replace(targetQuery, raplaceWithQuery)).then(function (response) {
                    array2 = response.data;
                    if (typeof (Storage) != "undefined") {
                        try {
                            window.localStorage.setItem("array2", JSON.stringify(array2));
                        } catch (e) {
                            window.localStorage.clear();
                            window.localStorage.setItem("array2", JSON.stringify(array2));
                            $ionicHistory.clearCache();
                            $ionicHistory.clearHistory();
                            $state.reload();
                            $scope.$state = $state;
                        }
                    }
                    $scope.formaspag = [];
                    for (lastPush = 0; lastPush < 100; lastPush++) {
                        if (angular.isObject(array2[lastPush])) {
                            $scope.formaspag.push(array2[lastPush]);
                        };
                    }
                }, function (response) {
                    // error message
                    var alertPopup = $ionicPopup.alert({
                        title: "error " + response.status,
                        template: response.statusText + "<br/>Ocorreu um problema na tabela de ofertas",
                    });
                }).finally(function () {
                    $scope.$broadcast("scroll.refreshComplete");
                    // event done, hidden animation loading
                    $timeout(function () {
                        $ionicLoading.hide();
                    }, 1000);
                });

            }, 1000);
        }



        $scope.doRefresh = function () {
            // retry retrieving data
            window.localStorage.clear();
            $http.get("http://vovocooks.com.br/admin/apis/api_listagem/lista_pagamentos.php?json=promocao".replace(targetQuery, raplaceWithQuery)).then(function (response) {
                array2 = response.data;
                if (typeof (Storage) != "undefined") {
                    try {
                        window.localStorage.setItem("array2", JSON.stringify(array2));
                    } catch (e) {
                        window.localStorage.clear();
                        window.localStorage.setItem("array2", JSON.stringify(array2));
                        $ionicHistory.clearCache();
                        $ionicHistory.clearHistory();
                        $state.reload();
                        $scope.$state = $state;
                    }
                }
                $scope.formaspag = [];
                for (lastPush = 0; lastPush < 100; lastPush++) {
                    if (angular.isObject(array2[lastPush])) {
                        $scope.formaspag.push(array2[lastPush]);
                    };
                }
            }, function (response) {
                // error message
                var alertPopup = $ionicPopup.alert({
                    title: "error " + response.status,
                    template: response.statusText + "<br/>problem: table ofertas",
                });
            }).finally(function () {
                $scope.$broadcast("scroll.refreshComplete");
                // event done, hidden animation loading
                $timeout(function () {
                    $ionicLoading.hide();
                }, 500);
            });



        };

        // FIM LEITURA DE FORMAS DE PAGAMENTO


        // PEGA $scope.formaspag (array2 no localstorage) E COMPARA COM OS CÓDIGOS DE FORNECEDORES_CONFIGURA_FRETE E IMPRIME NA TELA

        $scope.array1 = window.localStorage.getItem("tipos_pagamentos");

        $scope.array1 = $scope.array1.split(',');

        console.log($scope.array1);





        // AQUI VAI ENTRAR O CÓDIGO DE ESCOLHER A FORMA DE PAGAMENTO

        // MODAL PARA TROCO
        $ionicModal.fromTemplateUrl('templates/carrinho/modal/troco.html', {
            scope: $scope
        }).then(function (modal) {
            $scope.troco_modal = modal;
        });
        //CODE FOR MODAL ENDS HERE

        $scope.checkItems = {}

        console.log($scope.checkItems);

        $scope.print = function () {
            console.log($scope.checkItems);
        }

        $scope.pegaFormaPagamento = function () {
            var array = [];
            for ($scope.array1 in $scope.checkItems) {
                console.log($scope.checkItems[$scope.array1]);
                window.localStorage.setItem("forma_pagamento_selecionada", $scope.checkItems[$scope.array1]);

                if ($scope.checkItems[$scope.array1] === "Dinheiro") {

                    $state.go('nhaac.troco');



                } else {
                    $state.go('nhaac.entrega');
                }
            }

        }


        // event readmore
        $scope.onInfinite = function () {
            $timeout(fetchItems, 500);
        };

        // create animation fade slide in right (ionic-material)
        $scope.fireEvent = function () {
            ionicMaterialMotion.fadeSlideInRight();
            ionicMaterialInk.displayEffect();
        };


        // animation ink (ionic-material)
        ionicMaterialInk.displayEffect();
        $scope.rating = {};
        $scope.rating.max = 5;



        //       }
        //       else
        //        {
        //            console.log("Enter in the ELSE DE FORMA DE PAGAMENTO");
        //  $location.path('#/nhaac/entrar');
        //           $state.go("nhaac.entrar3");
        //       }

    })

})();

My View:

<ion-view view-title="forma de pagamento" hide-nav-bar="false" page-id="forma_pag" id="forma_pag" charset="utf-8">
<!-- content -->

<ion-content delegate-handle="top" lazy-scroll doRefresh()>

    <ion-list ng-repeat="ra in array1 track by $index" >
        <ion-radio ng-model="checkItems[ra]" ng-value="'{{ra}}'">{{ra}}</ion-radio>
    </ion-list>

    <button class="button button-full button-assertive" ng-click="pegaFormaPagamento(checkItems[ra])">
        CONTINUAR
    </button>

</ion-content>
<!-- ./content -->

And my index has the :

<head>
    <meta http-equiv="Content-Type" content="text/html;">
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

Ah, yes, I’ll pass my PHP:

<?php


header('Content-type: application/json;charset=UTF-8');
header('Access-Control-Allow-Origin: *');



include 'database.php';

$query="select * from formas_pagamento ORDER BY nome DESC";


$result=$con->query($query);

$row_cnt = mysqli_num_rows($result);
if ($result->num_rows > 0) 
{
    $count=0;
    echo "[";
    while($row = $result->fetch_assoc()) 
    {
            $count++;
            echo json_encode($row);

            if($count!=$row_cnt)
            {
                    echo ",";
            }


    }
    echo "]";
}
else
{
echo "error";
}

?>

How can I fix this accent problem?

Remembering that in the database everything is accented normal.

What could I be doing wrong?

Personal thank you. :)

1 answer

1


You are probably sending the answer from your Backend uncoded, you can set in your call get the type of data that will come in your reply.

In his controller, when you are performing the

$http.get('')

try to mount an object for your request that contains the Content-type:

$http({
    method: 'GET',
    url:'http://vovocooks.com.br/admin/apis/api_listagem/lista_pagamentos.php?json=promocao".replace(targetQuery, raplaceWithQuery)',
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    }
      }).then(function(response){
.....
.....
....
})

Or

During the configuration phase of your application, app.config(), use

$http.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';

Documentation:

  • 2

    in that link can format your answers.

  • Thanks, Fagner, it was worth too much. But I found that the error is in the registration and not in the listing... (dumb me), so I opened the question at: http://answall.com/questions/192614/erro-de-acentua%C3%A7%C3%A3o-com-xmlhttp-open-ou-no-php-usando-angujarjs-Ionic But Thanks! I already scored you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.