How to use .directive, modularization and layering? AngularJS

0

OBS: Until I understood the whole thing, the problem is that I can not do with this code the information that passed me, type nothing. And when I do it does not work. Can someone please help me ??

Hello, I have a serious problem with understanding how these things work in a text. I would like to create a .directive, make it modularize by making part of the code used in services and partitioning that code. I'm starting to learn now so I'm having a lot of trouble in this part of the Angular creation process.

angular.module('TarefApp', []);

// Code goes here
angular.module('TarefApp')

.controller('TarefasController', function($scope) {
  $scope.categorias = [];
  $scope.tarefas = [];
  $scope.categoriaTarefa = {
    tarefa: {}
  };

  $scope.addTarefa = function(tarefa) {
    if (!$scope.categoriaSelecionada) {
      alert("Selecione uma categoria!")
      return;
    }

    var c = $scope.categoriaSelecionada;

    if (!$scope.categoriaTarefa.tarefa[c])
      $scope.categoriaTarefa.tarefa[c] = [];
    else {
      var itemDuplicado = false;
      angular.forEach($scope.categoriaTarefa.tarefa[c], function(item, index) {
        itemDuplicado = (item.nome === tarefa.nome);
        if (itemDuplicado) {
          alert("Tarefa para categoria já existe!");
          return false;
        }
      });
    }

    if (!itemDuplicado) {
      $scope.categoriaTarefa.tarefa[c].push(tarefa);
      $scope.tarefa = {};
    }
  };

  $scope.delTarefas = function() {
    angular.forEach($scope.categorias, function(item) {
      var c = item.nome;
      var oldTarefas = $scope.categoriaTarefa.tarefa[c];
      $scope.categoriaTarefa.tarefa[c] = [];

      angular.forEach(oldTarefas, function(tar) {
        if (!tar.selecionado) $scope.categoriaTarefa.tarefa[c].push(tar);
      });
    });
  };

  $scope.addCategoria = function(categoria) {
    for (var i = 0; i < $scope.categorias.length; i++) {
      if ($scope.categorias[i].nome === categoria.nome) {
        alert("A categoria já existe!");
        return;
      }
    }
    $scope.categorias.push(angular.copy(categoria));
    delete $scope.categoria;
  };
});
        .container {
          margin-top: 2%;
        }
        .apgfiltro {
          margin-top: 5%;
          margin-bottom: 2.9%;
        }
        a:hover {
          text-decoration: none !important;
        }
        .done-true {
          text-decoration: line-through;
          color: #ccc;
        }
        .col-xs-9.edit {
          margin-top: 3%;
        }
<html lang="pt-br" ng-app="TarefApp">
<head>
<!-- Angular.js minificado  -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>


		<!-- Angular.js minificado  -->
		<script src="js/app.js"></script>
		<script src="js/controller/TarefasController.js"></script>
		<!-- Bootstrap -->
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script></head><body><divid="div-container" class="container ng-scope" ng-controller="TarefasController">
            <div class="row">
                <div class="col-xs-3">
                    <!-- Ínicio Adicionar Categoria -->
                    <div class="page-header">
                        <h4>Adicionar Categoria</h4>
                    </div>
                    <div id="div-form">
                        <form role="form" class="ng-pristine ng-valid">
                            <div class="form-group">
                                <input type="text" class="form-control ng-pristine ng-valid" ng-model="categoria.nome">
                            </div>
                            <button class="btn btn-info btn-block ng-pristine ng-valid" ng-click="addCategoria(categoria)" ng-model="infoIgual" ng-disabled="!categoria.nome" disabled="disabled">Adicionar</button>
                        </form>
                    </div>
                    <!-- Fim Adicionar Categoria -->
                    <!-- Ínicio Adicionar Tarefa -->
                    <div class="page-header">
                        <h4>Adicionar Tarefa</h4>
                    </div>
                    <div id="div-form">
                        <form role="form" class="ng-pristine ng-valid">
                            <div class="form-group">
                                <input type="text" class="form-control ng-pristine ng-valid" ng-model="tarefa.nome">
                                <br>
                                <select class="form-control" id="category" ng-options="item.nome as item.nome for item in categorias" ng-model="categoriaSelecionada">

                                </select>
                            </div>
                            <button class="btn btn-info btn-block ng-pristine ng-valid" ng-click="addTarefa(tarefa)" ng-model="infoIgual" ng-disabled="!tarefa.nome" disabled="disabled">Adicionar</button>
                        </form>
                    </div>
                    <!-- Fim Adicionar Tarefa -->
                </div>

                <!-- Categorias + Tarefas -->
                <div class="col-xs-9 edit">
                    <button class="btn btn-danger btn-block" ng-click="delTarefas()">Apagar tarefas selecionadas</button>
                    <div ng-repeat="categoria in categorias">
                        <h4 ng-model="categoria.selecionado">{{categoria.nome}}</h4>
                        <div ng-repeat="tarefa in categoriaTarefa.tarefa[categoria.nome]">
                            <input type="checkbox" ng-model="tarefa.selecionado" ng-click="tarefaFeita()">
                            <span class="done-{{tarefa.selecionado}}">{{tarefa.nome}}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
  	</body>
  </html>
    
asked by anonymous 09.10.2015 / 13:38

2 answers

1

Briefly, I'll explain how policies work.

1) to create a policy:

app.directive("nomeDaDiretiva", function () {
   //seu método 
});

2) to create a modulated policy:

angular.module('NomeDoModulo', [])
.directive("nomeDaDiretiva", function () {
   //seu método 
});

3) What happens is that we point the module to a variable:

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

4) So we created a directive:

app.directive("nomeDaDiretiva", function () {
   //seu método 
});

5) In the module we have to pass the elements that will be used in the application, as I put ngResource , ngRoute :

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

6) Policies contain some restrictions that can be defined:

   E - Restricted policy to element A - Restricted directive to element attribute C - Policy restricted to class of element
M - Policy restricted to element comment

Here is an example policy (note that in this example, it contains the EAC constraint (together) and is modularized: link

The policy will have a return, and it can contain the following parameters restrict, layout, method itself and replace, it will receive a Boolean (true or false).

It can also contain scope parameterization (escope):

angular.module('MeuSistema', [])
.directive('DadosUsuario', function () {    
    return {
        restrict: 'E',
        scope:{
           nome:'@',
           email:'@',
           cidade:'@'
        },
        template:'<div></div>',
        link: function(scope,element, attributes) {

            element[0].innerHTML =  'Os dados do usuário são:<br>'
             + 'Nome: ' + scope.nome + '<br>'
             + 'Email: ' + scope.email + '<br>'
             + 'Cidade: ' + scope.cidade;

        },
        replace: true
    };
}) //o correto é separar isso em um arquivo só do seu controller em uma pasta "controllers"
.controller('ExibirDados', function() {

  $scope.nome = "Larissa Mourullo";
  $scope.email = "[email protected]";
  $scope.cidade = "São Paulo";

});

And in HTML:

<html ng-app="MeuSistema">
 <title>Exemplo</title>
 <body ng-controller="ExibirDados as dados">

<dados-usuario nome="{{dados.nome}}"
               email="{{dados.email}}"
               cidade="{{dados.cidade}}">
</dados-usuario>

<script src="/directives/dados_usuario.js"></script>
<script src="/controllers/controller.js"></script>
</body>

</html>
    
09.10.2015 / 14:36
2

Come on:

First of all, you need to understand what a controller, service, and non-angular directive is

Controller

Understand item as being a controller of the components that are on screen. In other words, here are all the routines that involve user interaction with the HTML page itself. In addition, requests from other components such as the service also go from here.

Service

This is the guy responsible for sharing resources between the controllers, and here too are usually the routines that involve http calls. It is common for people to use this guy to make rest calls for example. That way you have a person service for example that can include, change, delete a person.

Generic Service

App.factory("$comum", function($http, $q, $injector) {
    function ajax(url, parametros, metodo) {
        var requisicao = $http({
            method: metodo,
            url: url,
            data:parametros
        });

        var promessa = requisicao.then(
            function(resposta) {
                return(resposta.data);
            },
            function(resposta) {
                return($q.reject("Something went wrong"));
            }
        );
        return promessa;
    }
    return({
        ajax:ajax
    });
});

Historical Service Sale

App.factory("$historicovenda", function($comum) {
    var historico;
    return {
        buscar : function(filtro) {
            var promessa = $comum.ajax("/fusion/services/roi/history/search", filtro, "POST");
            promessa.then(function(req) {  
                historico = req;
            })
            return promessa;
        },
        cache : function() {
            return historico;
        }
    };
});

Historical Controller Sale

App.controller("HistoricoVendaController", function($scope, $historicovenda) {
    $scope.buscar = function(regerar) {
        var filtro = "1";
        $historicovenda.buscar(filtro).then(function(req){
            console.log(req)
        });
    };
});

And now come to your question:

Layer Split

The division into layers is precisely to separate the responsibilities of each. A practical example: You have a person record, in which case we can divide the routine into two components. A controller ( layer 1 ) responsible for performing the action when the user clicks the save and validate the data button. In addition this component will also compile the object to be saved and then pass the ball to the service ( layer 2 ) that will make the http call to effect the user in the database. In this case we have two layers with low coupling. If you need to consult a person in another controller can use the same service. And there is the balcony to separate the responsibilities, you can share the resources.

Directive

The directive is used when you want to determine a behavior in a given HTML element. It can also be used for you to create your own tags. There are many angular libraries that make use of such an element to give a specific behavior. Example:

No Js:

angular.module('App', [])
.directive('sonClick', function () {    
    return {
        restrict: 'A',
        link: function(scope,element,attrs){
            element.bind('click',function(){       
                scope.$eval(attrs.sonClick);
            })
        }
    };
})
.controller('CtrlApp', function ($scope) {
    $scope.executa = function(){
        alert("scope");           
    };
});

No html:

<div ng-controller="CtrlApp">
    <button son-click="executa()">clique aqui</button>
</div> 

Modularization

This is the simplest and I consider as much as the others. It is about separating into different files each component. One file for controller, another for service, another for policy, and so on.

    
09.10.2015 / 14:42