Update $Scope in Angularjs

Asked

Viewed 7,017 times

4

Guys the problem, in a general way, is that I can’t take information received in a controller and apply it in my html, when I try instead of printing the variable on the screen becomes empty, when I give a console.log in my scope, the information is there available, but they’re not put on the screen when I need them.

So, I have a user search very similar to the 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;
        }
}

Where my list starts I can click on it, and send the user data through an 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 this function is requested the following modal is opened, where the idea is to insert all rescued user information.

<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>
  • Please put all the code I believe it’s easier to help you like this !!!

  • Yes, place the html otherwise it is impossible to decipher. But right off the bat it is very strange a function tied to an ng-click "receive" data. Generally, the data is linked to the variables placed in the form via ng-model.

  • Post your html code, it will be easier to find the error.

  • Your code has several "smells" that you are mixing the balls in the jQuery/Bootstrap way of doing things with the Angular way. A clear problem is that you should not have the same controller for 2 different views. I would advise you to take a look at the Angular UI Bootstrap or Angularstrap project and see an alternative way more "Angulariana" to do what you want to do.

  • Got it, thanks for the suggestion!

  • @Dema can explain what the smells are? As for a controller for a view, this is not a "Angularian standard".

  • @Bertrand In fact, Angular encourages you to break down your page into several smaller components and that each component of it has an associated, inter-connected controller by the Scope inheritance mechanism. But reusing the same controller for 2 different views is something unusual, which usually leads to a more complex controller than it should be.

Show 2 more comments

3 answers

2

The problem is that $scope.dados belongs to the controller’s Scope avaliacao and the search function belongs to the controller pesquisas. Avaliacao is the son of pesquisas, soon pesquisas does not have access to the child’s Interview.

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

The shape "angularian" to share models between controllers is to use a "service"

Look at this one 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>
<div ng-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>

  • 1

    This, on line 45, solves what many people are looking for -> $Scope.suser = {name: ',email: ''};

1

If the scope has the correct value but the data does not appear in the UI is because the Digest Cycle did not occur once the data returned and so Angular does not update the data links (data Binds).

This is probably because the request for user data is asynchronous (more details on search() would be useful).

Try placing the code below after user data has been added to the scope.

$scope.$apply();

This command starts a Digest Cycle and causes Angular to check if any change has occurred, if it finds any difference it performs the necessary updates, which in your case are the data links in the UI.

A hint, in the research form you don’t need to use the ng-keyup and ng-keydown directives together, one of them is enough.

  • When I add this line I am presented with the following error.http://docs.angularjs.org/error/$rootScope/inprog? P0=$apply

  • I solved the problem with using $rootScope :D

  • That’s not the problem. The variables within $Scope are "Watched" by default. The problem is that data_user belongs to a different Scope.

  • @user7443 You must not use $rootScope to display models among controllers (see http://stackoverflow.com/questions/14573023/is-binding-objects-to-angulars-rootscope-in-a-service-bad)

0

first time contributing to the content...

I used the method applied by the Bertrand user, but using this way $rootScope. $apply();

And you need to parse into your code where to place this line of code, because if it’s used in an execution that $Digest() is still in progress it won’t work.

thanks for the tip.

Browser other questions tagged

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