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

Asked

Viewed 918 times

1

I’m making a list and I want to pass the values of a model to the algular 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 to fetch 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.

2 answers

3

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

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

$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 would look 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 questions of the comment.

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

It is necessary to use response.data because the object returned by $http is composed of:

  • config
  • date
  • headers
  • statusText

If you only want to get the data, you must use response.data. But with the whole object you can do other checks, such as 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;
}

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

About the injection would be this here: controller($scope, $http), the same way you did with the $scope. I just commented to let you know that this step is mandatory.

1

I was having the same problem, what I did: I passed the content that had dendro from my php variable in the form of json to angular 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 userController controller inside the list function, where I have a $usertable variable containing user information from my database and so Seto for the $user variable

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

That way.

Browser other questions tagged

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