$Scope does not visually update the data I fill with Javascript

Asked

Viewed 472 times

0

I’m filling in mine $scope via Javascript using the following code:

    myApp.controller('gruposController', ['$scope', '$http', '$window', 'usuariosFactory', '$timeout', function ($scope, $http, $window, membrosFactory, $timeout) {
    // Cria um namespace para os dados do formulário
    $scope.formData = {
        /* Inicializa os participantes / aprovadores para que não seja preciso
         * validar no controller principal
         */
        participantes: [],
        aprovadores: []
    };

    // [...]
    function atualizarGrupo(id) {
    // Promisse para processar a requisição
    var grupoPromise = $scope.getGrupo(id);
    grupoPromise.then(
        // Função para executar caso tudo ocorra normalmente
        function(response) {
            // Mostra a tela
            $('.fancy-inline-group[href="#add-group"]').click();

            var grupo = angular.fromJson(response.data);

            $scope.formData.grupo = grupo.grupo;
            $scope.formData.descricao = grupo.descricao;

            // Reseta os participantes e aprovadores
            $scope.formData.aprovadores = [];
            $scope.formData.participantes = [];
            var usuarios = grupo.usuarios;

            // Lógica para preencher os aprovadores e participantes
            if (usuarios.length > 0) {
                angular.forEach(usuarios, function(usuario, key) {
                    var usuarioID = usuario.id;
                    $scope.formData.participantes.push(usuarioID);
                    if (usuario.pivot.aprovador == 1) {
                        $scope.formData.aprovadores.push(usuarioID);
                    }
                });
            }

            // Aplica as mudanças ao objeto $scope
            $timeout(function() {
                console.log($scope.formData);
                $scope.$apply();
            });
        },
        function(response) {
            console.log('Error: ' + response.statusText);
        }
    );
}

Below, how is the HTML:

    <div id="add-group" ng-controller="gruposController">
    <h1><strong>Adicionar</strong> Grupo</h1>
    <hr />
    <form action="" class="form-horizontal">
        <input type="hidden" name="id" value="" ng-model="formData.id" />
        <div class="form-group">
            <label for="name" class="col-sm-2 control-label">Nome do grupo*</label>
            <div class="col-sm-10">
                <input type="text" name="grupo" ng-model="formData.grupo" class="form-control" value="" required="required" placeholder="">
            </div>
        </div>
[...]

The Binding when typing a value in inputs occurs correctly, just like when I run a console.log($scope) it shows the correct data, but the inputs do not update in the form. I saw that when executing the $scope.$apply() in the $timeout theoretically I would update my $scope visually, but this did not happen.

  • 1

    Usually this happens because the fields that should be updated are outside the scope of the controller that you defined post also html pf

  • 1

    Another thing, where you declared the $Scope?

  • updated the issue with the codes you requested. The Binding default (by changing the values of inputs) works normally. The problem is in manually sending JS values to inputs. I believe only then.

  • Do a test. Remove the value="" attribute from your input

  • Same thing. Actually this I inserted later for other purposes.

  • http://www.jeffryhouser.com/index.cfm/2014/6/How-do-I-run-code-when-a-variable-changes-with-AngularJS It says here the problem is that to update $Scope you need to interact with the user, so it’s not working. Only, in my case, I need a fancybox to open now with the data (my application is virtually 100% Ajax).

  • post your source in jsfiddle.net for some tests

Show 2 more comments
No answers

Browser other questions tagged

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