A
A
Andrey2015-09-13 15:47:39
Angular
Andrey, 2015-09-13 15:47:39

Why is data refresh not working in AngularJS?

Hello!
Just started learning AngularJS and ran into a problem. The data from the controller is not updated. Here is the controller code:
testController.js

appTest.controller('testController', function ($scope,$document,$http) {
  $scope.datasize = 0;
  $scope.itemPerPage = 3;
  $scope.showOnPage = 0;
  $scope.page = 0;

  $scope.load = function () {
    $http.get('http://localhost/test/test.json').success(function (data) {
      $scope.licenses = data;
      $scope.datasize = data.length;
      $scope.isDataEmpty();
      $scope.makePagination();
    });
  };

  $document.on('ready',function() {
    $scope.load();
  });

  $scope.isDataEmpty = function() {
    var licTable = angular.element(document.querySelector('.lic-table'));
    var emptyAlert = angular.element(document.querySelector('.message'));
    if ($scope.datasize === 0) {			
      licTable.css('display','none');
      emptyAlert.addClass('show');
    }
    else {
      licTable.css('display','table');
      emptyAlert.removeClass('show');
    }
  };

  $scope.setPage = function(page) {
    var newPage = page * $scope.itemPerPage;				
console.log(newPage);
    $scope.showOnPage = newPage;
  };

  $scope.makePagination = function() {
    var pageCount = Math.ceil($scope.datasize / $scope.itemPerPage);
    var pagination = angular.element(document.querySelector('.pagination'));
    for (var i = 0; i < pageCount; i++) {
      var a = angular.element('<a>');
      a.attr('href','#'+i);
/* Здесь вешаем событие, для переключения страниц. Но при клике ничего не обновляется */
      a.on('click',function(e){				
        var page = e.target.text;
/* Хотя в лог пишутся данные */
        $scope.setPage(page);
      });
      a.text(i);			
      pagination.append(a);
      var li = angular.element('<li>');
      if ($scope.page === i) {
        li.addClass('active');
      }

      a.wrap(li);
    }
  }

});

index.html
<!DOCTYPE html>
<html lang="" ng-app="appTest">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AngularJS Test</title>
    <style type="text/css">
      .hide {
        display: none;
      }
      .show {
        display: block;
      }
    </style>

    <!-- Bootstrap CSS -->
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div ng-controller="testController">
      <div class="alert alert-info hide message">Нет записей для отображения!</div>
      <table class="table table-strict lic-table" >
          <thead>
            <tr>
              <th>ID</th>
              <th>KEY</th>
              <th>EMAIL</th>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="lic in licenses | limitTo: itemPerPage : showOnPage">
                <td>{{lic.id}}</td>
                <td>{{lic.key}}</td>
                <td>{{lic.email}}</td>
            </tr>
          </tbody>
      </table>
      <ul class="pagination">
        
      </ul>
      <h1 ng-bind="showOnPage"></h1>
    </div>
    <script src="//code.jquery.com/jquery.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
    <script type="text/javascript" src="controllers/testController.js"></script>
  </body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arthur, 2015-09-13
Haylov @scrolllocker

Angular does not know anything about the click hung via the .on() method - therefore, after the click, Angular needs to be forced to inform about the scope refresh:

a.on('click', function(e) {				
    var page = e.target.text;

    $scope.setPage(page);

    // обновляем скоуп
    $scope.$apply();
});

Regarding everything in general:
The controller should have only logic - forget about zhiQuery, forget about selectors, get the zhiQuery approach out of your head - controllers do not know anything about DOM elements, only logic in controllers.
You need to hide / show elements not in a Zhikverevian way, through the .css () method (working with the DOM), but in an Angular way, through ng-show (working with logic).
You need to set classes not in the Zhikverevian way, through the .addClass () method (working with the DOM), but in the Angular way, through ng-class (working with logic) (moreover, you set the .show / .hide classes - no classes are needed here , then use ng-show , because you show / hide ).
There is no need to insert elements into the DOM, this is done directly in HTML, and not in the controller:
<ul class="pagination">
    <li ng-repeat="page in pages">{{page}}</li>
</ul>

You need to hang events on elements not in the Zhikverevian way, but directly in HTML:
<ul class="pagination">
    <li ng-repeat="page in pages" ng-click="openPage(page)">{{page}}</li>
</ul>

And in general, there should be a regular link, not a click event:
<ul class="pagination">
    <li ng-repeat="page in pages">
        <a ng-href="/page/{{page}}">{{page}}</a>
    </li>
</ul>

And most importantly - remove ZhiQuery. It is not needed at all, at all, throw out the very concept of liveQuery from the brain, throw out the way of thinking on liveQuery - Angular works in a completely different way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question