Good practices for changing variables $Scope

Asked

Viewed 661 times

4

Follow an example of code:

Controller:

$scope.filterText = {status: 'Todos', tipo: 'Todos'};
$scope.params = {page: 1, total: 10, orderBy: 'id', sort: 'desc', search: {status: '',tipo: ''}};

$scope.filterStatus = function(status, text) {
    $scope.params.search.status = status;
    $scope.filterText.status = text;
    getProjetos($scope.params);
};

$scope.filterTipo = function(tipo, text) {
    $scope.params.search.tipo = tipo;
    $scope.filterText.tipo = text;
    getProjetos($scope.params);
};

HTML:

<a class="btn btn-default" ng-click="filterStatus(1, 'Execução')">Status: {{filterText.status}}</a>
<a class="btn btn-default" ng-click="filterTipo(1, 'Laboratório')">Tipo: {{filterText.tipo}}</a>

To change the text of the buttons and the parameters of the query I do the assignment from inside the function without passing by parameter, changing $Scope directly, but it should not be a good practice.

I change the $scope.params because I want to save the state of the query, for example if I click the two buttons, the first arrow the $scope.params.status = 1 and does the search, when you click on the second arrow $scope.params.tipo = 1 and makes the search, still keeping the $scope.params.status = 1 in this second search.

What are good practices for changing variables $scope and what is the best solution in this situation?

1 answer

4


Its implementation attempts to control the flow of events programmatically and synchronously (filterStatus > stores status and texto > getProjetos()).

You can benefit from the asynchronous nature of Javascript and behavior dual Binding of Angular, thus simplifying both its process and its code:

inserir a descrição da imagem aqui

angular.module('myApp', [])
.controller('myController', function($scope){
  $scope.selected = {};                     // Armazena a seleção do usuário
  $scope.statuses = [1,2,3,4,5]             // Possíveis estados
  $scope.tipos = ["A", "B", "C", "D"];      // Possíveis tipos

  $scope.$watch('selected', function(val) { // Monitora mudanças 
                                            // no valor de $scope.selected

    console.log('A seleção mudou:', val);   // Ou, no seu caso, chame 
                                            // getProjetos();
  }, true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div ng-app="myApp">
  <div ng-controller='myController'>

    Status: 
    <select ng-model="selected.status">
      <option ng-repeat="s in statuses" value="{{s}}">{{s}}</option>
    </select>

    Tipo: 
    <select ng-model="selected.tipo">
      <option ng-repeat="t in tipos" value="{{t}}">{{t}}</option>
    </select>

    <br>

    {{selected }}

  </div>
</div>

Browser other questions tagged

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