Update $ scope in AngularJS

4
The problem, in a general way, is that I can not pick up information I received on a controller and apply it to my html, when I try to print it instead the variable on the screen is empty when I give console.log on my scope, the information is there available but they are not put on the screen when I need it.

So, I have a user search very similar to facebook.

<form class="navbar-form navbar-left" role="search" ng-controller="pesquisas">
   <div class="form-group">
                        <input type="text" ng-keyup="search()" ng-keydown="search()" ng-model = "pesquisa.nome_usuario" class="form-control pesquisar_input" placeholder="Pesquisar">
                    </div>
                    <!-- <button type="submit" class="btn btn-default">Pesquisar</button> -->
                    <div class = "resultado_pesquisa" ng-show="resultado>0">
                        <ul>
                            <li class = "linha_usuario_pesquisa"ng-repeat = "usuario in usuarios " data-refresh-list data-toggle="modal" href='#avaliacao' ng-click="dados_usuario(usuario)" ng-controller="avaliacao" >
                                <div class = "imagem_perfil_masculino pull-left" ng-show="usuario.sexo_usuario==1">
                                    <span class="glyphicon glyphicon glyphicon-user usuario_masculino" ></span>
                                </div>
                                <div class = "imagem_perfil_feminino pull-left" ng-show="usuario.sexo_usuario==0">
                                    <span class="glyphicon glyphicon glyphicon-user usuario_masculino" ></span>
                                </div>
                                <span class = "nome_linha_usuario pull-left" >{{usuario.nome_usuario}}</span>
                            </li>
                        </ul>
                    </div>
                </form>

The controller that performs the search is this.

$scope.search = function(){



        if($scope.pesquisa.nome_usuario.length >0){
            $http.post('usuarios/consult_user',$scope.pesquisa)
            .success(function(data){
                $scope.resultado = 1;
                $scope.usuarios = data;


            });

        }
        else{
            $scope.resultado = 0;
            $scope.usuarios = 0;
        }
}

When you start my list I can click on it, and send the user data through a ng-click, my controller that receives this information is as follows.

 app.controller('avaliacao', function ($scope, $http) {
        $scope.dados = {};
        $scope.dados_usuario = function (usuario) {
            $scope.dados = usuario;
        });
    });

At the same time that this function is requested, the following modal is opened, where the idea is to enter all the user information that has been retrieved.

<div class="modal fade " id="avaliacao"  data-backdrop="static" ng-controller="avaliacao">
            <div class="modal-dialog full-screen">
                <div class="modal-content" >
                    <div class="modal-body">
                        <div class="navbar navbar-fixed-top nav-interna">

                            <div class = "imagem_perfil_masculino_interno pull-left" >
                                <span class="glyphicon glyphicon glyphicon-user usuario_masculino" ></span>
                            </div>
                            <span class="pull-left nome_aluno_interno" ><h4 >{{dados.nome_usuario}}</h4></span>


                            <button type="button" class="close pull-right" data-dismiss="modal" aria-hidden="true">&times;</button>


                        </div>
                    </div>
                </div>
            </div>
        </div>
    
asked by anonymous 08.04.2014 / 04:35

3 answers

2

The problem is that $scope.dados belongs to the scope of the avaliacao driver and the search function belongs to the pesquisas driver. Avaliacao is the child of pesquisas , so pesquisas does not have access to the scope of the child.

User $ $ RootScope to overcome this problem is a bad practice ( see this post in the SO in English )

The "angular" way of sharing templates between controllers is to use a "service"

See here this PLUNKR as an example of what you want.

      angular
        .module("myApp", [])
        .factory('utilizadores', [function() {
            return [
              { nome: 'joao', email: '[email protected]' },
              { nome: 'maria', email: '[email protected]' },
              { nome: 'rita', email: '[email protected]' }
            ];
        }])
        .controller('lista', ['$scope', 'utilizadores', function($scope, utilizadores) {
          $scope.utilizadores = utilizadores;
          $scope.pesquisado = false;
        }])
        
        .controller('pesquisa', ['$scope', 'utilizadores', function($scope, utilizadores) {
          $scope.suser = {nome: '',email: ''};
          var list = utilizadores;
          console.log(list);
          $scope.pesquisar = function (name) {
            for (var i=0; i<list.length; ++i) {
              if (list[i].nome === name) {
                $scope.suser = list[i];
                break;
              }
            }
          }
        }])
        
        .directive('userDetails', function() {
              return {
                template: 'Nome: {{suser.nome}} Email: {{suser.email}}'
              };
        })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script><divng-app="myApp">
    <div ng-controller="lista">
    <span ng-repeat="utilizador in utilizadores">
      Nome: {{ utilizador.nome }} - mail: {{ utilizador.email }}<br>
    </span>
    </div>
  
  
    <div ng-controller="pesquisa">
      Pesquisar: <input type="text" ng-model="name"> <button ng-click="pesquisar(name)">Pesquisar</button>
      
      <div user-details>
        
      </div>
      
    </div>
</div>
    
02.05.2014 / 09:04
1

If the scope has the correct value but the data does not appear in the UI it is because the digest cycle did not occur once the data returned and therefore Angular does not update the data binds.

This probably occurs because the request of the user data is asynchronous (more details about search () would be useful).

Try putting the code below once the user data is added to the scope.

$scope.$apply();

This command starts a digest cycle and causes Angular to check if any changes have occurred. If it finds any differences, it performs the necessary updates, which in your case are the data links in the UI.

One tip, in the search form you do not need to use the ng-keyup and ng-keydown policies together, one of them is sufficient.

    
11.04.2014 / 11:43
0

first time contributing content ...

I used Bertrand's user-implemented method, but using $ rootScope $ apply ();

And you have to analyze in your code where to put this line of code, because if it is used in an execution that $ digest () is still in progress it will not work.

Thanks for the tip.

    
28.10.2016 / 14:26