MVC - pass a php variable to the angular.js controller

1

I am making a listing and want to pass the values of a model to the algebra script that is in the view.

Model:

 function getAllDisplayable_all()
 {
    $this->db->select('id_menu, nome, descricao, preco, foto');
    $result = $this->db->get('menus');
    return $result->result();
 }

script:

 <script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [ 
         'teste',
        //quero passar as variaveis php para aqui
        ];
    });
</script>

html listing:

<div class="row">
            <div class="table-responsive">
             <table class="table table-hover">
                <thead>
                    <tr>
                     <th>Nome</th>
                     <th>Preço</th>
                    </tr>
                </thead>
             <tbody id="myTable">
                <tr ng-repeat="x in names | filter:test">
                 <td>{{ x }}</td>
                </tr>
             </tbody>
         </table> 
        </div>
        </div>
    </div>

Normally I have gone fetching the data as follows:

<?php foreach ($list as $menus): ?>
                      <div class="pr">
                          <?php echo $menus->nome?>
                      </div>
          <?php endforeach ?>  

But this time I need to use angular.js. Thank you.

    
asked by anonymous 09.06.2016 / 16:25

2 answers

2

To do this, you need to make a request to get the data because it is not possible to insert% of php directly into the angle, as done in a view, for example.

For this you need to use the service $http , thus:

$http.get('sua/url/arquivo.php').then(
    function(response) {
        //Executado com sucesso
        $scope.valor = response.data;
    },
    function(error) {
        //Algo deu errado
        console.info('algo deu errado:', error);
    }
)

In your example, it looks like this:

angular.module('myApp', []).controller('namesCtrl', function($scope, $http) {
    $http.get('sua/url/arquivo.php').then(
        function(response) {
            $scope.names = response.data;
        },
        function(error) {
            console.info('algo deu errado:', error);
        }
    )
});

Note that you need to inject the service into your controller .

Answering the comment questions.

//Sim, aqui você coloca o caminho para o arquivo onde está obtendo os dados
$http.get('url/arquivo.php')... 

You must use response.data because the object returned by $ http is composed of:

  • config
  • data
  • headers
  • statusText

If you just want to get the data, you should use response.data . But with the whole object you can do other checks, such as the return status, whether it was 200 or 404, for example, as follows:

if(response.status == 404) {
    alert('arquivo não encontrado);
} else if (response.status == 200) {
    $scope.names = response.data;
}

There are more options we have to do a better job. To learn more, I recommend read more about the $http service .

About injection would be this: controller($scope, $http) , just like you did with $scope . I just told you to know that this step is mandatory.

    
09.06.2016 / 16:32
0

I had the same problem, which I did: I passed the content that had dendro of my variable php in json form to the angle variable in your example, it would look like this.

    <script>
  angular.module('myApp', []).controller('namesCtrl', function($scope, $http) {

    $scope.names = <?php echo json_encode($user); ?>;
  });
</script>

meu html ficou assim

     <tbody>
                <tr ng-repeat="(key, value) in names  | filter:pesquisa">
                  <td>{{value.username}} </td>
                  <td>{{value.email}}</td>
                </tr>
              </tbody>

Just to point out, I'm using cakephp3, so the $ user variable is coming from my controller userController inside the function list, where I have a $ usertable variable where it contains user information from my bank and so I set it to $ user variable

$this->set('user', $user);

This way.

    
29.06.2016 / 15:34