N
N
nfuture2014-02-18 15:59:37
JavaScript
nfuture, 2014-02-18 15:59:37

How to implement asynchronous data loading in AngularJS template?

Hello.
I can't implement data loading using ajax in an AngularJS template.
I am doing on the basis of this example jsfiddle.net/derkoe/Wk7WD/presentation
Only, my data should be loaded into the list.html
app.js template

var app = angular.module('app', []).config(function ($routeProvider) {
    $routeProvider.when('/list', {
        templateUrl: 'views/list.html',
        controller: 'ListCtrl'
    , resolve: {
            load: function ($route, dataService) {
         return dataService.load();
            }
        }
    }).otherwise({
        redirectTo: '/list'
    });
});

app.controller('ListCtrl', function ($scope, $location, dataService) {
       $scope.data = dataService.data;
  
  consol.log(dataService.data);
  
    $scope.back = function () {
        $location.path('/list');
     };
});


app.factory('dataService', function ($q) {
    return { 
        data : {},
        load : function() {
            var defer = $q.defer();
            var data = this.data;
      
    /*
           код из примера
            $timeout(function () {
                data.id = id;
                defer.resolve(data);
            }, 1000);
  */
    
                // -- здесь пока обычный jquery-ajax-запрос
                // -- знаю что в AngularJS есть $http , но пока не научился им пользоваться
                // -- если знаете, покажите с использование $http
 		$.ajax({
      type: 'GET',
       url: 'backend/?route=notes:list',
      success: function(response) {
        $scope.notes = response.data.notes;
        
 				console.log(response);
        
 				data.notes = response.data.notes;
                                defer.resolve(data);
      },
       error: function (req_obj, msg, error) {
        console.log('Ошибка запроса');
      },
      dataType: 'json'
    });
               //----------------
    
    });	
            return defer.promise;
        }
    };
});

It is necessary that the data be loaded into the template asynchronously, but this does not happen.
load is not called at all consol.log(dataService.data); , also does not print data from the server.
Though from the server the data correctly come.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>AngularJS</title>
 </head>

 <body ng-app="app">
    <div ng-view></div>

  <script src="lib/jquery-1.10.2.js"></script>
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-resource.js"></script>

  <script src="js/app.js"></script>

</body>
</html>

list.html
Тестовый список {{test}}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
agladkov, 2014-03-19
@nfuture

1. In addition to $http, you can also use $resource
Your example

$http.get('backend/?route=notes:list').success(function (data) {
  ...
});

2. if you have calls that are not controlled by AngularJS, for example, callback from $.ajax, then operations on $scope must be wrapped in $scope.$apply
3. you have an error in the code: consol e .log
4. @maxaon says it all
5. the load passed to the ListCtrl will contain a promise, not a dataService
6. in the example you refer to, the controller learned about the dataService not through resolve, but through a dependency, which you do the same, in the example, resolve is rather used as implicit calling the dataService.load method with the desired parameters instead of passing them to the controller
7. the callback passed to $.ajax knows nothing about $scope
In general, replacing $.ajax with $http, remove $scope from success, correct console and most likely it will start. Leave dataService to the controller.

M
maxaon, 2014-02-18
@maxaon

Keys from resolve are injected by key into the controller, so you need to
Or change the name in 'resolve' accordingly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question