Help in Deletion and Angular Editing

Asked

Viewed 686 times

1

Good afternoon ! I’m not being able to create the functionality of editing and removing an object from an angular array, could someone help me ? follows below the code of the controller and the service :

angular.module("appOS").controller("CadastroServicoCtrl",function($scope, Servicos,$location,$timeout){
	
  $scope.servicos = Servicos.listar();
  
  $scope.adicionarServico = function(servico){
    $scope.exibirMsg = false;
    
    var id = $scope.servicos.length;
    servico.codigo = (id + 1);
    Servicos.adicionar(angular.copy(servico));
    delete $scope.servico;
    $scope.servicoForm.$setPristine();
    
      $timeout(function(){
      $scope.exibirMsg = true;
      $scope.mensagem = "Serviço Cadastrado com Sucesso!";
      }, 2000);
      
	};



});

angular.module("appOS").factory("Servicos", function(){
	var servicos = [];
	return {
		listar: function(){
			return servicos;
		},
		adicionar: function(servico){
			
			servicos.push(angular.copy(servico));
			delete servico;
		},
		remover:function(id){
			
		}
	}

});

  • Any of the answers helpful? Don’t forget to choose one and mark it so you can!

2 answers

0

In particular, I advise you not to use Factory that way, especially since its variable is inside Factory, I don’t know how your application works, but if that Factory goes through the injection system by being called elsewhere, it should end up zeroing out that variable of yours, but nothing prevents you from having the methods in Factory.

angular.module("appOS")
.controller("CadastroServicoCtrl",function($scope, arrayFactory){

  var ctrl = this;

  var arr = [];

  arrayFactory.add(arr, "valorAdd");

  arrayFactory.edit(arr, "valorAddModificado", null, "valorAdd"); // Edit por valor
  // arrayFactory.edit(arr, "valorAddModificado", 0, null); Edit por Index

  arrayFactory.remove(arr, null, "valorAddModificado"); // Remove por Valor
  // arrayFactory.remove(arr, 0, null); Remove por Index
});

angular.module("appOS").factory("arrayFactory", function(){
  return {
    add: function (arr, value) {
      arr.push(value);
      return arr;
    },

    edit: function (arr, newValue, index, oldValue) {
      if (index) {
        arr[index] = newValue;
        return arr;
      } else if (oldValue) {
        arr.forEach(function (item) {
          if (item == oldValue) {
            item = newValue;
          }
        });
        return arr;
      }
    },

    remove: function (arr, index, value) {
      if (index) {
        arr.splice(index, 1);
        return arr;
      } else if (value) {
        arr.forEach(function (item, index) {
          if (item == value) {
            arr.splice(index, 1);
          }
        });
        return arr;
      }
    }
  }
});

0

Follow an example of CRUD with all operations. Although it seems like a tutorial I believe it is what you need to remedy your doubts.

var app = angular.module("Aplicacao", []);

app.controller("ControllerCliente", ["$scope",
  function($scope) {
    $scope.clienteSelecionado = {};
    $scope.clientes = [];
    $scope.novoCliente = true;
    console.log("O Controller iniciou.");

    $scope.cadastrar = function() {
      if ($scope.novoCliente) {
        $scope.clientes.push($scope.clienteSelecionado);
      }

      $scope.novoCliente = true;
      $scope.clienteSelecionado = {};
    };

    // Objeto no javascript trabalha com referência
    $scope.selecionar = function(indice) {
      $scope.novoCliente = false;
      $scope.clienteSelecionado = $scope.clientes[indice];
    };

    $scope.excluir = function(indice) {
      $scope.clientes.splice(indice, 1); // Apaga n registros de um vetor a partir de um índice
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="Aplicacao">
  <div ng-controller="ControllerCliente">
    {{clienteSelecionado}}
    <br>
    <form>
      <fieldset>
        <legend>Cadastro de Cliente</legend>

        <div>
          <label for="edtNome">Nome</label>
          <input type="text" name="edtNome" ng-model="clienteSelecionado.nome">
        </div>

        <div>
          <label for="edtSobrenome">Sobrenome</label>
          <input type="text" name="edtSobrenome" ng-model="clienteSelecionado.sobrenome">
        </div>

        <div>
          <button ng-click="cadastrar()">Cadastrar</button>
        </div>
      </fieldset>
    </form>

    {{clientes}}

    <table border=1>
      <thead>
        <tr>
          <th>Nome</th>
          <th>Sobrenome</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="cliente in clientes">
          <td>{{cliente.nome}}</td>
          <td>{{cliente.sobrenome}}</td>
          <td>
            <button ng-click="selecionar($index)">Selecionar</button>
            <button ng-click="excluir($index)">Excluir</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Browser other questions tagged

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