How to use . Directive, modularization and layer splitting? Angularjs

Asked

Viewed 1,026 times

0

NOTE: Until I understood everything, the problem is that I can not do with this code the information that I passed, like nothing. And when I do not work. Can someone please help me??

Hello, I have a serious problem in understanding how these things work quoted in a text. I would like to create one . Directive, make the modularization part of the code be used in services and perform the division of layers in that code. I’m starting to learn now so I’m having a hard time with 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>
		<script src="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>
	    <div id="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>

  • You want a lot in a single question, in this case I recommend you take the course up to the free phase that Angularjs itself offers [ http://campus.codeschool.com/courses/shaping-up-with-angular-js/ ] , with it you will have all the foundation necessary to start creating each of these elements.

  • For more information, please refer to the documentation: https://docs.angularjs.org/api

2 answers

2

Come on:

First of all you need to understand what is a controller, a service and a directive at the angle

Controller (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, the requisitions to other components such as the service.

Service ()

This is the guy responsible for sharing resources between controllers and also here are usually the routines involving http calls. It’s common for people to use this guy to make Rest calls for example. This 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
    });
});

Historic Service For 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;
        }
    };
});

Controller Histórico Venda

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

And now for your question:

Layering

The division in layers is precisely to separate the responsibilities of each one. A practical example: You have a person registration, in this case we can divide the routine into two components. A controller (layer 1) responsible for performing the action when the user clicks the save button and validate the data. 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 on another controller you can use the same service. And there’s the point of separating the responsibilities, you can share the resources.

Directive (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 libraries at the angle 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");           
    };
});

In 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’s about separating into different files each component. A file for controller, another for service, another for directive and so on.

inserir a descrição da imagem aqui

1


Briefly, I will explain how the directives work.

1) to create a directive:

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

2) to create a modulated directive:

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) Then we create 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) The Directives contain some restrictions that can be defined:

And - Directive restricted to the element
To - Directive restricted to element attribute
C - Directive restricted to element class
M - Directive restricted to element comment

Here is an example of a directive (note that in this example, it contains the EAC constraint (together) and is modularized: http://jsfiddle.net/ivanferrer/1cyxoytv/

The directive will have a return, and it may contain the following parameters restriction (restrict), layout (template), method itself (link) and substitution (replace), it will receive a boolean (true or false).

May also contain scope parameterization (scope):

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>

Browser other questions tagged

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