How do I populate a $ scope (angular) with get.Json (jquery)?

2

I have a PHP application and use $.getJSON of jQuery to fetch data and thus submit it to my user. I would like to populate a table using Angular. How do I fill a $scope with the response of $.getJSON ?

Code sample below (without the part of the table)

<code>
<script type="text/javascript">
    jQuery(document).ready(function(){
    $(function(){
        $("#formulario").submit(function(){
            $.getJSON('arquivo.php', function(retorno){
                //quero pegar esse retorno e jogar no $scope do angular que esta abaixo e assim,
                // deixar o angular popular minha tabela
                        }); 
        });
    });
    });

  // angular --- Aqui abaixo estou preenchendo a minha tabela com os dados abaixo...
  // neste caso estão manual. Quero que os dados abaixo sejam dinamicos.. vindo da tabela.
  // Imagino que esse não deve ser o jeito certo de fazer isso, todavia não sei como faze-lo.
  var ctrlLog = function($scope){
        $scope.loggers = [
            {nome_controller:'login',nome_action:'logar'},
            {nome_controller:'login',nome_action:'logar'},
            {nome_controller:'login',nome_action:'logar'},
            {nome_controller:'login',nome_action:'logar'},
            {nome_controller:'login',nome_action:'logar'},
        ];
  };

</script> 
</code>
    
asked by anonymous 27.02.2014 / 14:23

3 answers

3

With Angular, while not preventing other shapes, you stop working with $.getJSON and start using its own functions, such as $http :

<table>
    <tr> <!-- Cabeçalho -->
        <th>X</th>
        <th>Y</th>
        <th>Z</th>
    </tr>
    <!-- Dados da tabela: -->
    <tr ng-repeat="coordenda in dados">
        <td>{{coordenada.x}}</td>
        <td>{{coordenada.y}}</td>
        <td>{{coordenada.z}}</td>
    </tr>
</table>
  $http({
    method: 'GET', // ou 'POST'
    url: urlDoSeuJSON
  }).success(function(data, status) {
    $scope.dados = data;
  });

Example in JSFiddle (not mine) | Example based on question author data .

$http is a service of AngularJS. They help organize the code by abstracting common functions for web applications, simplifying their development.

    
27.02.2014 / 14:33
1

The most recommended is to do as Gustavo said ... go using the functions of AngularJS.

But in the case of your code, the simplest solution is to place the function where it has access to $scope . So:

<script type="text/javascript">
  var ctrlLog = function($scope){
        $scope.loggers = [
            {nome_controller:'login',nome_action:'logar'},
            {nome_controller:'login',nome_action:'logar'},
            {nome_controller:'login',nome_action:'logar'},
            {nome_controller:'login',nome_action:'logar'},
            {nome_controller:'login',nome_action:'logar'},
        ];
        $("#formulario").submit(function(){
            $.getJSON('arquivo.php', function(retorno){
                // pronto! aqui o teu código tem acesso direto à variável $scope
            });
        });
  };
</script> 

Note : this is far from ideal! Something more appropriate would be to define a service to communicate with the server using $http , inject it into controller , and use it to update any property of $scope passing -o as parameter:

var ctrlLog = function($scope, $myService){
    $scope.loggers = [
        {nome_controller:'login',nome_action:'logar'},
        {nome_controller:'login',nome_action:'logar'},
        {nome_controller:'login',nome_action:'logar'},
    ];
    $scope.submitHandler = function() {
        $myService.updateLoggers($scope);
    };
};
    
27.02.2014 / 22:22
0

Use an Angular $ resource to make the requests and add this $ resource to a service.

    var services = angular.module('services', ['ngResource']);
    services.factory(
        'Modelo-a-ser-requisitado',
        ['$resource',
        function ($resource) {
                return $resource('/api/modelo/:controller:modeloId', {modeloId: '@modeloId', controller: '@controller'},
            {
                pesquisa: {
                    method: 'GET',
                    params: {
                        modeloId: '@modeloId'
                    },
                    isArray: true
                }
            }]);

Since the $ resource already comes with the implicit methods ($ get, $ list and $ save), just call.

To embed in the code just popular the object in scope

    Controllers.controller('Ctrl',
    ['$scope', 'Recurso',
    function ($scope, Recurso) {
        $scope.variavel = Recurso.pesquisa({modeloId: 1}, function () {
            //função de callback, puramente opcional
        });
    
13.05.2014 / 15:07