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

Asked

Viewed 1,028 times

2

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

Code example below ( without table part )

<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>
  • 2

    It would be more indicated that you post a code snippet of how far you have already reached, given that the focus of the group are specific programming questions

3 answers

3

With Angular, not preventing other forms, you stop working with $.getJSON and uses his 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 (it’s not mine) | Example based on question author data.

The $http is a service of Angularjs. They help in the organization of code by abstracting common functions for web applications, simplifying their development.

1

The most recommended is to do as Gustavo said... using Angularjs' own functions.

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

<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> 

Observing: this is far from ideal! Something more appropriate would be to define a service to communicate with the server using $http, inject it into the controller, and use it to update any property of $scope passing it as a 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);
    };
};

0

Use an Angular $Resource to make the requests and add that $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 $Resource already comes with implicit methods ($get, $list and $save), simply call.

To embed in the code simply populate the object in the scope

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

Browser other questions tagged

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