2016-05-13 299 views
1

當我在加載頁面後立即訪問list.html時,它並沒有顯示出列表。我需要先去form.html,然後返回到list.html,然後它給了我列表。當我在控制器中有$ http函數時,它按照我的想法工作,但現在它們在服務中,它們不像以前那樣工作。AngularJS ng-init不起作用

app.js

app.service("dataservice", function($http){ 

    var list = [{}]; 

    this.get = function(){ 
     $http.get("harjoitus22/backend.php").success(function(response){ 
      list = response; 
     }); 
    }; 

    this.save = function(newcontact){ 

     $http({ 
      method: 'post', 
      url: 'harjoitus22/backend.php', 
      data: newcontact, 
      header: 'Access-Control-Allow-Origin: *' 
     }).success(function(response){ 
      list = response;    
     });   
    }; 

    this.give = function(){ 
     return list; 
    }; 
}); 

app.controller("mainController", function($scope, $location, dataservice){ 

    $scope.save = function(){  
     dataservice.save($scope.newcontact); 
     $scope.newcontact = {}; 
     $location.path("/list"); 
     $scope.list = dataservice.give(); 
    }; 

    $scope.get = function(){ 
     dataservice.get(); 
     $scope.list = dataservice.give(); 
    }; 
}); 

list.html

<tbody ng-init="get()"> 
     <tr ng-repeat="object in list"> 
      <td>{{object.nimi}}</td> 
      <td>{{object.email}}</td> 
      <td>{{object.ruoka}}</td> 
      <td>{{object.sauna}}</td> 
     </tr> 
    </tbody> 

回答

3

$http調用以異步方式工作,當你調用它,它不會給你的下一行執行響應。要留意那個ajax,你應該使用promise返回$http方法。

爲了實現你需要從服務get方法返回承諾對象相同($http方法確實回報的承諾的對象,它可以幫助你在.then功能的搭建到執行代碼)。

服務

this.get = function(){ 
    return $http.get("harjoitus22/backend.php").then(function(res){ 
     list = res.data; 
    }); 
}; 

控制器

dataservice.get().then(function(){ 
    $scope.list = dataservice.give(); 
}); 
+1

不是 「可能」,但 「應該」 嘿嘿 –

+1

@AndrewDonovan嘿嘿:D固定。 :p感謝提供男人.. –

+1

哈哈沒有probs! –