Wednesday, 15 February 2012

ajax - Angular js adding template to the page with data fetched asynchronously from the server -



ajax - Angular js adding template to the page with data fetched asynchronously from the server -

i have template booktemp.html:

<div ng-repeat="book in books"> <div class="foo" ng-include src="'app/templates/book.html'"></div> </div>

in index.html file have container div:

<div ng-include src="'app/templates/booktemp.html'" ng-controller='bookcontroller'></div>

and controller bookcontroller code is:

app.controller("bookcontroller", function($scope, $http, $compile){ $http.defaults.headers.common.accept = 'application/json'; var responsepromise = $http.get('http://localhost:8080/books'); responsepromise.success(function(data, status, headers, config) { $scope.books= data; //do }); responsepromise.error(function(data, status, headers, config) { alert("ajax failed!"); }); }

to fetch books' info server using ajax request.

mt question is: best practice populate template "books" info , add together page. way written no book shown because request asynchronized , when template rendered there no books' info in $scope because request hasn't returned yet.

should write whole directive or instead "load" or utilize $compile in way add together page 1 time request returns (in line says "do something").

i've tried thing of kind:

var htmlcontent = $('.bookscontainer'); htmlcontent.load('app/templates/booktemp.html', $scope.articles, somecallback);

and also:

var htmlcontent = $('.bookscontainer'); htmlcontent.load('app/templates/booktemp.html' $compile(htmlcontent.contents())($scope);

but didn't work.

thanks.

edit: lot expertsystem. code made me realize problem else. turns out path of different templates in "src" attribute wrong. i've changed prefix "." base of operations url , add together total path (with in app) after wards. if 1 knows of improve practice happy learn.

ajax angularjs asynchronous

No comments:

Post a Comment