Adding the edit function in a single Form in Angularjs

Asked

Viewed 1,241 times

0

I am starting to have contact with Angularjs and I developed a simple application of registration, where I can insert and delete data. But I’m having trouble implementing the editing function.

I’m using only one Form and I’m trying to maintain the function of editing using this same form. But I still can’t make it work properly. Below are the codes I made with the last change to the edit function.

<!DOCTYPE html>
<html ng-app="cadastro">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>BonilhaTech - Cadastro de Usuários</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>
        .usuario-conteudo {
            background-color: #EEE;
            padding: 20px 20px 10px 20px;
            margin-top: 30px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-offset-2 col-md-8">
            <div class="usuario-conteudo" ng-controller="UsuarioController">
                <div class="boasvindas" >
                    <h1 style="text-align: center"> {{myHeader}} </h1>
                </div>                
                <h1>Cadastro de Usuários</h1>
                <form name="formulario" ng-if="update">
                    <div class="form-group">
                        <label for="nome">Nome*</label>
                        <input type="text" class="form-control" id="nome" placeholder="Nome do usuário" 
                               maxlength="20" required ng-model="usuario.nome">
                    </div>
                    <div class="form-group has-feedback {{statusSenha.classe}}">
                        <label for="senha">Senha*</label>
                        <input type="password" class="form-control" id="senha" placeholder="Informe a senha do Usuário" 
                               maxlength="10" required ng-model="usuario.senha" ng-change="validarSenha()">
                        <span class="glyphicon form-control-feedback {{statusSenha.icone}}" aria-hidden="true"></span>
                        <p class="help-block">{{statusSenha.mensagem}}</p>
                    </div>
                    <div class="form-group has-edit">
                        <label for="nome">Para editar os dados, utilizar os campos abaixo:</label>
                        <input type="text" class="form-control" placeholder="Altere o nome do usuário" maxlength="20" 
                               required ng-model="update.name">
                        <input type="password" class="form-control" required ng-model="update.senha"placeholder="Altere a senha do Usuário"
                               maxlength="10" ng-change="validarSenha()">
                        <span class="glyphicon form-control-feedback {{statusSenha.icone}}" aria-hidden="true"></span>
                        <p class="help-block">{{statusSenha.mensagem}}</p>
                    </div>
                    <button type="submit" class="btn btn-primary" ng-submit="cadastrar()">Cadastrar</button>
                    <button ng-click="salvar()" ng-submit="salvar()" class="btn btn-primary">Editar</button>
                </form>
                <hr>
                <h1>Lista de Usuários: </h1>
                <table class="table table-striped" ng-hide="UsuarioController.usuarios == 0">
                    <thead>
                    <tr>
                        <th>Nome</th>
                        <th>Senha</th>
                        <th>Ação</th>
                    </tr>
                    </thead>
                    <tbody>
                    <!-- Aqui serão exibidos os dados do usuários cadastrados -->
                        <tr ng-repeat="usuario in usuarios">
                            <td>{{usuario.nome}}</td>
                            <td>{{usuario.senha}}</td>
                            <td><button class="btn btn-danger btn-xs" ng-click="remover($index)">Remover</button></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>


</body>

</html>

Javascript Code of the Controller:

(function() {
'use strict';

angular.module('cadastro', [])

.controller('UsuarioController', function($scope, $timeout) {

    //mensagem de Boas-Vindas
    $scope.myHeader = "BemVindo!";
    $timeout(function() {
        $scope.myHeader = "Welcome!";
    }, 5000);
    // lista de usuários pré cadastrados
    $scope.usuarios = [
        { nome: 'Guerra', senha: '1234' },
        { nome: 'Jô', senha: '12345' },
        { nome: 'Pratto', senha: '12345678' },
        { nome: 'Ricardo Oliveira', senha: '1234' }
    ];

    //inicialização de um usuário vazio
    $scope.usuario = { nome: '', senha: '' };

    //método para adicionar o usuário a lista
    $scope.cadastrar = function() {
        $scope.usuarios.push($scope.usuario);
        $scope.usuario = { nome: '', senha: '' };
    };

    //método para remover o usuário da lista
    $scope.remover = function(index) {
        $scope.usuarios.splice(index, 1);
    };
    //método para validar a senha do usuário
    $scope.validarSenha = function() {
        $scope.statusSenha = {
            classe: '',
            icone: '',
            mensagem: ''
        };

        if ($scope.usuario.senha && $scope.usuario.senha.length >= 8) {
            $scope.statusSenha.classe = 'has-success';
            $scope.statusSenha.icone = 'glyphicon-ok';
            $scope.statusSenha.mensagem = 'Esta senha é forte, parabéns cabaço!';
        } else {
            $scope.statusSenha.classe = 'has-error';
            $scope.statusSenha.icone = 'glyphicon-remove';
            $scope.statusSenha.mensagem = 'Faça um favor a si mesmo, apaga isso e tente novamente.';
        }
    };
    //método para salvar e editar o nome e senha do usuário
    $scope.editar = function(user, i) {
        $scope.update = angular.copy(user);
        index = i;
    }
    $scope.salvar = function() {
        $scope.users[index] = $scope.update; 
        $scope.update = ""; 
    }
});

});

})();
  • 1

    You can’t do what?

  • I am not able to make the edit work in this register. I saw alternatives but using another form or even generating a new html page. I’m trying to do it in one.

  • It’s really hard to understand what your difficulty is, John. Specifically what’s going wrong?

  • Good Night Jbueno, the problem is that the edit function is not working, only the register or remove function. I looked for other ways to edit in the same form but was unsuccessful.

1 answer

0


John, I’ve made a few adaptations to your code and it looks like it’s working just fine. I recommend that you study more Angularjs and all its validations, because what you have done can be improved.

Plunker: http://plnkr.co/edit/xqTlJq3c6XGDpwDBKY6x?p=preview

HTML:

<!DOCTYPE html>
<html ng-app="cadastro">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>BonilhaTech - Cadastro de Usuários</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>
        .usuario-conteudo {
            background-color: #EEE;
            padding: 20px 20px 10px 20px;
            margin-top: 30px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-offset-2 col-md-8">
            <div class="usuario-conteudo" ng-controller="UsuarioController as ctrl">
                <div class="boasvindas" >
                    <h1 style="text-align: center"> {{myHeader}} </h1>
                </div>                
                <h1>Cadastro de Usuários</h1>
                <form name="formUsuario" ng-if="usuario" novalidate>
                    <div class="form-group">
                        <label for="nome">Nome*</label>
                        <input type="text" class="form-control" id="nome" placeholder="Nome do usuário" 
                               maxlength="20" required ng-model="usuario.nome">
                    </div>
                    <div class="form-group has-feedback {{statusSenha.classe}}">
                        <label for="senha">Senha*</label>
                        <input type="password" class="form-control" id="senha" placeholder="Informe a senha do Usuário" 
                               maxlength="10" required ng-model="usuario.senha" ng-change="validarSenha()">
                        <span class="glyphicon form-control-feedback {{statusSenha.icone}}" aria-hidden="true"></span>
                        <p class="help-block">{{statusSenha.mensagem}}</p>
                    </div>
                    <button ng-click="cancelar()" class="btn btn-default">Cancelar</button>
                    <button ng-click="salvar(usuario)" class="btn btn-primary">Salvar</button>
                </form>
                <hr/>
                <h1>Lista de Usuários: </h1>
                <table class="table table-striped" ng-hide="usuarios.length === 0">
                    <thead>
                    <tr>
                        <th>Nome</th>
                        <th>Senha</th>
                        <th>Ação</th>
                    </tr>
                    </thead>
                    <tbody>
                    <!-- Aqui serão exibidos os dados do usuários cadastrados -->
                        <tr ng-repeat="usuario in usuarios">
                            <td>{{usuario.nome}}</td>
                            <td>{{usuario.senha}}</td>
                            <td>
                              <button class="btn btn-primary btn-xs" ng-click="editar(usuario)">Editar</button>
                              <button class="btn btn-danger btn-xs" ng-click="remover(usuario)">Remover</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <button class="btn btn-primary" ng-click="cadastrar()">Cadastrar</button>
            </div>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>


</body>

</html>

JS:

(function() {
'use strict';

angular.module('cadastro', [])
  .controller('UsuarioController', function($scope, $timeout) {
    //mensagem de Boas-Vindas
    $scope.myHeader = "BemVindo!";
    $timeout(function() {
        $scope.myHeader = "Welcome!";
    }, 5000);

    // lista de usuários pré cadastrados
    $scope.usuarios = [
        { id: 1, nome: 'Guerra', senha: '1234' },
        { id: 2, nome: 'Jô', senha: '12345' },
        { id: 3, nome: 'Pratto', senha: '12345678' },
        { id: 4, nome: 'Ricardo Oliveira', senha: '1234' }
    ];

    //inicialização de um usuário vazio
    $scope.usuario = null;

    //método para 
    $scope.cadastrar = function() {
      var maxId = Math.max.apply(Math, $scope.usuarios.map(function(u) { return u.id; }));
      $scope.usuario = { id: ++maxId, nome: '', senha: '' };
    };

    //método para remover o usuário da lista
    $scope.remover = function(usuario) {
      var index = $scope.usuarios.map(function(u) { return u.id; }).indexOf(usuario.id);
      $scope.usuarios.splice(index, 1);
    };

    $scope.cancelar = function() {
      $scope.usuario = null;
    };

    //método para validar a senha do usuário
    $scope.validarSenha = function() {
        limpaStatusSenha();

        if ($scope.usuario.senha && $scope.usuario.senha.length >= 8) {
            $scope.statusSenha.classe = 'has-success';
            $scope.statusSenha.icone = 'glyphicon-ok';
            $scope.statusSenha.mensagem = 'Esta senha é forte, parabéns cabaço!';
        } else {
            $scope.statusSenha.classe = 'has-error';
            $scope.statusSenha.icone = 'glyphicon-remove';
            $scope.statusSenha.mensagem = 'Faça um favor a si mesmo, apaga isso e tente novamente.';
        }
    };
    //método para editar o usuário
    $scope.editar = function(usuario) {
      $scope.usuario = angular.copy(usuario);
      $scope.validarSenha();
    }

    $scope.salvar = function(usuario) {
      var indexAtualizado = $scope.usuarios.map(function(u) { return u.id; }).indexOf(usuario.id);
      if (indexAtualizado < 0) {
        $scope.usuarios.push(usuario);
      } else {
        $scope.usuarios[indexAtualizado] = usuario; 
      }
      $scope.usuario = null;
      limpaStatusSenha();
    }

    function limpaStatusSenha() {
      $scope.statusSenha = {
          classe: '',
          icone: '',
          mensagem: ''
      };
    }
  });
})();
  • Thank you Waldir, I will make the adjustments in my code. I am studying Angularjs for a little while and I am really enjoying its resources. I’m going to review this validation part because I may have missed something.

  • Ok. Remember to mark the answer as valid, if it helped you.

Browser other questions tagged

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