2
\$\begingroup\$

I never took an application in a Model-View-Controller architecture and have some difficulties in front-end. The following code works fine, but what can I do to make "layers" of better code and even the application directories?

This is a single file located in /resources/js/controller.js.

Controller.js

var app = angular.module('app', ['ngRoute']);

app.config(function ($routeProvider) {
    $routeProvider.when('/cadastro', {
        controller: 'veiculoController',
        templateUrl: '/tpl-cadastrar.tpl'
    }).when('/', {
        controller: 'indexController',
        templateUrl: '/tpl-index.tpl'
    }).when('/info/:id', {
        controller: 'infoController',
        templateUrl: '/tpl-info.tpl'
    });
});

app.controller('veiculoController', function ($scope, $http) {
    $scope.contatos = [{
        nome: "",
        email: ""
    }];
    $scope.selecionados = [];

    $scope.listaAgencias = ["Exemplo 1", "Exemplo 2", "Exemplo 3"];

    $http.get("/api/agencias")
        .success(function (data) {
            var embedded = data._embedded;
            // $scope.listaAgencias = embedded.agencias;
            //listaAgencias will set here
        }).catch(function (error) {
            alert("Erro ao obter listagem de agencias");
            console.log(JSON.stringify(error));
        });

    $scope.salvar = function () {
        var jsonObj = {
            nome: $scope.nome,
            tipo: $scope.tipo/*,
             agencias: $scope.selecionados,
             contatos: $scope.contatos*/
        };

        alert(JSON.stringify(jsonObj));

        $http.post("/api/veiculos", jsonObj)
            .success(function (data, status, headers, config) {
                $scope.nome = null;
                $scope.tipo = null;
            }).error(function (data, status, headers) {
                alert("Erro ao salvar dados do veiculo!");
                console.log(status + "\n" + JSON.stringify(data));
            });
    };

    $scope.cancelar = function () {
        window.location.href = "/"
    };

    $scope.novoContato = function () {
        $scope.contatos.push({
            nome: "",
            email: ""
        });
    };

    $scope.excluirContato = function () {
        var ultimoItem = $scope.contatos.length - 1;
        $scope.contatos.splice(ultimoItem);
    };

    $scope.selecionarAgencia = function (agencia) {
        $scope.selecionados.push(agencia);
        var index = $scope.listaAgencias.indexOf(agencia);
        $scope.listaAgencias.splice(index, 1);
    };

    $scope.removerAgencia = function (agencia) {
        $scope.listaAgencias.push(agencia);
        var index = $scope.selecionados.indexOf(agencia);
        $scope.selecionados.splice(index, 1);
    };

});

app.controller('indexController', function ($scope, $http) {
    $scope.init = function () {
        $http.get("/api/veiculos")
            .then(function (data) {
                var embedded = data.data._embedded;
                $scope.resultado = embedded.veiculos;
            }).catch(function (error) {
                alert("Erro ao obter dados");
                console.log(JSON.stringify(error));
            });
    };

    $scope.adicionarNovo = function () {
        window.location.href = "/#/cadastro";
    };

    $scope.excluir = function (resultado, index, url) {
        if (confirm('Tem certeza que deseja remover?')) {
            $http.delete(url).then(function (data) {
                resultado.splice(index, 1);
            }).catch(function (error) {
                alert("Erro ao excluir!" + error);
            });
        }
    };

    $scope.visualizar = function (url) {
        url = url.replace("http://localhost:8181/api/veiculos/", "");
        window.location.href = "/#/info/" + url;
    };
});

app.controller('infoController', ['$scope', '$routeParams', '$http', function ($scope, $routeParams, $http) {
    $http.get("/api/veiculos/" + $routeParams.id)
        .then(function (data) {
            var json = data.data;
            $scope.veiculoNome = json.nome;
            $scope.veiculoTipo = json.tipo;
            $scope.agencias = ["Exemplo 1", "Exemplo 2", "Exemplo 3"];
            $scope.contatos = json.contatos;
        }).catch(function () {
            window.location.href = '/';
        });

    $scope.removerAgencia = function (agencia) {
        if (confirm('Tem certeza que deseja remover?')) {
            var index = $scope.agencias.indexOf(agencia);
            $scope.agencias.splice(index, 1);
        }
    };

}]);

app.controller('modalController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
    $scope.salvarInformacoes = function () {
        var jsonObj = {
            nome: $scope.novoVeiculo,
            tipo: $scope.novoTipo
        };
        $http.patch("/api/veiculos/" + $routeParams.id, jsonObj)
            .then(function (data) {
                $scope.veiculoNome = $scope.novoVeiculo;
                $scope.veiculoTipo = $scope.novoTipo;
            }).catch(function (error) {
                alert("Erro ao atualizar veículo!" + "\t" + JSON.stringify(error));
            });
    }
}]);
\$\endgroup\$
2
\$\begingroup\$

In general, I recommend the John Papa's styleguide: https://github.com/johnpapa/angular-styleguide

modules
  news/
    news.module.js -> To define your module and dependencies
    news.constants.js -> all constants - can be accessible from .config 
    news.mocks.js -> data to use in TDD

    news.directive.js
    news.directive.spec.js

    news.controller.js
    news.controller.spec.js

    news.factory.js
    news.factory.spec.js

Comments on your code:

angular
  .module('newsApp.news', []);


angular
  .module('newsApp.news')
  .constants('MYCONS', {});


angular
  .module('newsApp.news')
  .directive('myDirective', MyDirective);

  MyDirective.$inject = ['myFactory'];

  /*@ngInject*/
  function MyDirective(myFactory) { }


angular
  .module('newsApp.news')
  .factory('myFactory', MyFactory);

  MyFactory.$inject = ['myFactory'];

  /*@ngInject*/
  function MyFactory(myFactory) {

    activate();

    return {
      getAll: getAll
    };

    function activate() {
      // trigger something
    }

    function getAll() {
      return {}
    }
  }

Note: I've noticed that you create methods for the controller. It's a good practice to move all that to a service factory.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.