Good practices for changing $ scope variables

4

Here is an example 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 inside the function without going through the parameter, directly changing the $ scope, but it should not be a good practice.

I change the $scope.params because I want the query state to be saved, for example if I click the two buttons, the first arrow the $scope.params.status = 1 and does the search, when I click on the second arrow the $scope.params.tipo = 1 e does the search, still holding the $scope.params.status = 1 in the second search.

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

    
asked by anonymous 11.01.2017 / 14:14

1 answer

4

Your implementation tries 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 the dual binding behavior of the Angular, simplifying both your process and your code:

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><divng-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>
    
11.01.2017 / 15:22