2

Hi I want to post item to server, and with each successful addition, automatically add it to DOM with ng-repeat

<div class=""  ng-repeat="book in books" >
   <div id="eachBook">{{book.title}}</div>
</div>

to POST the data and also to upload an image file, I use Jquery ajax, and $state.go(".") to reload the current page:

var fd = new FormData();
fd.append("file", bookImage);

$http({ 
    method: 'POST',
    url: "/someurl,
    data: fd,
    headers: {
        'Content-Type': undefined
    }
}).success(function(Image){
     var book_obj = {
         bookTitle: bookTitle,
         bookImage: Image._id
     };
     $http.post("url to owner book", book_obj)
         .success(function(data){
                 $scope.bookImage = data.bookImage;
             $timeout(function(){
                 alert("success", "successfully added your book");
                 $state.transitionTo('book', {}, { reload: true });
             },2000);                   
         })

})

The problem is with first addition, the DOM is still empty, and even though I use $state to reload the page, it still not working for the first addition. In the end I need to refresh the page manually by clicking refresh.

after the first addition, it works fine. With each book added, it automatically added to DOM..

Any idea how to automatically start the first one without manually rendering the page? using $timeout to delay the refresh has no effect.

vdj4y
  • 2,649
  • 2
  • 21
  • 31

1 Answers1

0

Is it not just a simple post to list on success?

var app = angular.module('myApp', []);
app.controller('bookCtrl', function($scope, $http, $timeout) {

  $scope.init = function(){
    $scope.title = 'initial book?'
    postBook();
  };
  $scope.books = [];

  $scope.post = function() {
    postBook();
  };

  function postBook(){
     if (!$scope.title) return;
    // timeout to simulate server post
    $timeout(function() {
      $scope.books.push({title:$scope.title});
      $scope.title = null;
    }, 1000);
  };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="bookCtrl" ng-init="init()">

  <div class="" ng-repeat="book in books">
    <div class="eachBook">{{book.title}}</div>
  </div>
  
  <input type="text" ng-model="title" /><button ng-click="post()">save</button>

</div>

EDIT: Not sure why your DOM isn't ready but how about ng-init to accomplish an initial book post?

Lee.Winter
  • 700
  • 9
  • 16
  • it still not working, even with $timeout.. I mean still the same problem, need to refresh manually.. – vdj4y Dec 05 '15 at 19:01
  • @vdj4y I have obviously misunderstood the problem. Could you make a snippet of the problem for us so we can see the issue? timeout was simply used to simulate your post delay – Lee.Winter Dec 05 '15 at 19:06
  • apologize, using $timeout makes no difference. I update the question with latest code, thanks – vdj4y Dec 05 '15 at 19:23