Form Angularjs with ng-repeat

Asked

Viewed 529 times

2

This is guys Blz?!

I’m new to Angularjs.

I’m developing a form but I can’t do ng-model abstraction. Follow the code below for better understanding.

<- JS ->

/* CONFIGURAÇÃO DO FORM */
        $scope.cfgForm = {
            item: {
                field: ["nome", "idade", "funcao"],
                headers: ["Nome", "Idade", "Função"],
                icon: ["person", "date_range", "business_center"]
            }
        };
        /* DADOS */
        $scope.clientes = [
            {nome: "Pablo Mendoça", idade: 25, funcao: "Estagiário"},
            {nome: "Ricardo Leite", idade: 41, funcao: "Diretor"},
            {nome: "Francisco Motta", idade: 35, funcao: "Gerente de Contas"}
        ];

        /* FUNÇÕES */
        /* ADICIONAR CLIENTE */
        $scope.addCliente = function(cliente){
            console.log(cliente);
        };

<- HTML ->

<div>
                        <!--{{cfgForm.item.field[k]}}-->
                        <md-input-container md-no-float class="md-block" ng-repeat="(k,field) in cfgForm.item.field">
                            <label>{{cfgForm.item.headers[k]}}</label>
                            <md-icon><i class="material-icons" >{{cfgForm.item.icon[k]}}</i></md-icon>
                            <input ng-model="cliente.field" type="text">
                            <!--{{cliente.field}}-->
                        </md-input-container>
                        <!--Botões de ação do Card-->
                        {{cliente.field}}
                        <md-card-actions layout="row" layout-align="end center">
                            <md-button class="md-icon-button" ng-click="addCliente(cliente)">
                                <i class="material-icons" >add_box</i>
                                <md-tooltip  md-direction="left">
                                    Adicionar
                                </md-tooltip>
                            </md-button>
                        </md-card-actions>
                    </div>
                </md-card-content>

Well, what happens is that when I put the add button in ng-repeat it abstracts the data and shows in the console, however it cannot repeat, IE, the button should stay out of ng-repeat. As I am shown above.

In this section of the code for example:

{{client field.}}

When I remove the comment in 1º {{client.field}} it makes the right bind. However the 2º {{client.field}} that is already outside ng-repeat does not. and what I need is just for that to do, so I can pass the data on ng-click that is outside ng-repeat.

I’d like the help!

  • 1

    Before offering a definitive answer. I identified that Voce has a list of customers on top within a table. And below What do you want to show the information of a particular client? How does the code know which client it will display below? Either Voce needs to provide this through a click, or at least the controllers need to start by telling which customer is selected to display the data below.

4 answers

1

Opa! ;)

Try to do it here:

 <input ng-model="cliente[field]" type="text">

In the previous way, you were giving bind to the object field of cliente, but you want to access the object whose name is contained in the variable field, then let us go to the notation of brackets! ;)

  • Hello Rodmentou, thanks for the tip. I was successful because in the generation of Json comes the name of "field". The problem now is that I can’t recover this information outside of repeat. Can you help me?

  • @Rickbatera, you can explain better? :)

1

<!DOCTYPE html>
<html ng-app="ornamentum">
<head>
    <title>ORNAMENTUM</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <!--Importação da folha de estilo principal--> 
    <link rel="stylesheet" type="text/css" href="lib/angular-material/angular-material.css">
    <link rel="stylesheet" type="text/css" href="style/material-icons/material-icons.css">
    <link rel="stylesheet" type="text/css" href="lib/angular-material/angular-material.layouts.css">
     <!--Importação da folha de estilo secundário e personalizados--> 
    <link rel="stylesheet" type="text/css" href="style/my-table.css">


     <!--Importação dos scripts principais--> 
    <script src="lib/angular/angular.js"></script>
     <!--Grupo de importações correnpondente ao ANGULAR-MATERIAL--> 
    <script src="lib/angular-animate/angular-animate.js"></script>
    <script src="lib/angular-aria/angular-aria.js"></script>
    <script src="lib/angular-material/angular-material.js"></script>
    <script src="lib/angular-messages/angular-messages.js"></script>
     <!--Grupo de importações correnpondente ao ANGULAR-MATERIAL--> 

     <!--Script inline--> 
    <script>
        // Nomeando o Módulo e fazendo carregamento dos módulos dependentes
        var ornamentum = angular.module("ornamentum", ["ngMaterial"]);
        // Controles
        ornamentum.controller('TituloCtrl', function ($scope) {
            $scope.title = 'Clientes';
        });
        ornamentum.controller('TabelaCtrl', function ($scope) {
            //Este trecho foi retirado de Toolbar

            /* CONFIGURAÇÃO DO FORM */
            $scope.cfgForm = {
                item: {
                    field: ["nome", "idade", "funcao"],
                    headers: ["Nome", "Idade", "Função"],
                    icon: ["person", "date_range", "business_center"]
                }
            };
            /* DADOS */
            $scope.clientes = [
                {nome: "Pablo Mendoça", idade: 25, funcao: "Estagiário"},
                {nome: "Ricardo Leite", idade: 41, funcao: "Diretor"},
                {nome: "Francisco Motta", idade: 35, funcao: "Gerente de Contas"}
            ];

            /* FUNÇÕES */
            /* ADICIONAR CLIENTE */
            $scope.addCliente = function (field) {
                console.log(field);
            };
        });
    </script>

</head>

<body>

    <div ng-cloak>
        <md-content class="md-padding" layout="row" layout-wrap layout-align="center start" layout-xs="column">
            <div flex="50" flex-xs="100" layout="column">

                <md-card>
                    <!--Topo-->
                    <md-toolbar md-scroll-shrink ng-if="true" ng-controller="TituloCtrl" class="md-card-image" >
                        <div class="md-toolbar-tools">
                            <h3>
                                <span>{{title}}</span>
                            </h3>
                            <span flex></span>
                            <!--Botões de ação-->
                            <md-card-actions layout="row" layout-align="end center">
                                <md-button class="md-icon-button">
                                    <i class="material-icons md-light" >add_box</i>
                                    <md-tooltip  md-direction="left">
                                        Adicionar Usuário
                                    </md-tooltip>
                                </md-button>
                            </md-card-actions>
                        </div>
                    </md-toolbar>

                    <!--Corpo do Card-->
                    <md-card-content ng-controller="TabelaCtrl">
                        <!--Tabela-->
                        <table class="md-table">


                            <thead>
                                <tr>
                                    <th class="md-table-header" ng-repeat="i in cfgForm.item.headers">
                                        <a href="">{{i}}</a>
                                    </th>
                                </tr>
                            </thead>


                            <tbody>
                                <tr ng-repeat="c in clientes">
                                    <td class="md-table-content" ng-repeat="(k, v) in c">{{v}}</td>
                                </tr>
                            </tbody>

                        </table>

                        <br />
                        <hr />



                        <div>
                            {{cfgForm.item.field[k]}}
                            <md-input-container md-no-float class="md-block" ng-repeat="field in cfgForm.item.field">
                                <label>{{cfgForm.item.headers[$index]}}</label>
                                <md-icon><i class="material-icons" >{{cfgForm.item.icon[$index]}}</i></md-icon>
                                <input ng-model="cliente[field]" type="text">
                                {{cliente}}
                            </md-input-container>
                            </div>
                            <!--Botões de ação do Card-->
                            <pre>{{cliente[0].nome}}</pre>                           
                            <md-card-actions layout="row" layout-align="end center">
                                <md-button class="md-icon-button" ng-click="addCliente(cliente[0].nome)">
                                    <i class="material-icons" >add_box</i>
                                    <md-tooltip  md-direction="left">
                                        Adicionar
                                    </md-tooltip>
                                </md-button>
                            </md-card-actions>


                    </md-card-content>
                </md-card>

            </div>
        </md-content>
    </div>

</body>

1

To add the client you must select it, through a link within ngRepeat (may or may not be the whole line) to a method that passes the item to a Scope variable and through the Scope variable you do what you need by clicking the button. something like that:

<div ng-repeat="item in items">
    // restante do código aqui
    <a ng-click="selecionar(item)">Selecionar</a>
</div>

<button ng-click="adicionar()">Adicionar</button>

$scope.items = [...];

$scope.itemSelecionado = [];

$scope.selecionar = function(item) {
    $scope.itemSelecionado = item;
}

$scope.adicionar = function() {
    console.log($scope.itemSelecionado);
}

Otherwise you must add directly from ngRepeat with an add button for each item, but you have already indicated that you do not want this behavior.

0

It’s working because your ng-repeat is doing an interaction across the fields ["nome", "idade", "funcao"]

That is, for Voce to access the client data outside the repeat, vc must provide the name of the fields explicitly: {{cliente.nome}},{{cliente.idade}},{{cliente.funcao}}

  • Hello Rogerio. Thank you for your help. I did what you told me, but I was not successful. Could you help me?

  • I forgot too, Voce must provide the customer’s input Voce wants the name. IE. {{cliente[0].nome}}

  • Thanks for the help Rogério. Unfortunately no obitive success again. I’ll put the whole code to see what happens Ok?!

  • Would be of great value !

  • 1

    Rogerio Barreto couldn’t edit the question, so I added the code down there as a comment.

  • name of its vector is clientes so try to clientes[0].nome

Show 1 more comment

Browser other questions tagged

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