2015-04-22 73 views
0

我的控制器有問題。我使用離子(角度)和js數據。當我通過addItem()添加一個新項目時,只有當我通過F5重新加載頁面時纔會看到它。

這裏是我的代碼:

.controller('FooCtrl', function($scope, $ionicPlatform, foo) { 
    $ionicPlatform.ready(function() { 
     foo.findAll().then(function (items) { 
      $scope.items = items; 
     }); 
    }); 

    $scope.item = {}; 
    $scope.addItem = function() { 
     foo.create({ name: $scope.item.name }); 
    }; 
}) 

我有什麼做的,看到withous首先按F5的新元素在我的瀏覽器窗口?

+2

你必須'push'新項目到您的集合:'$ scope.items.push($ scope.item)' – DRobinson

回答

1

要創建一個項目,並更新數據庫。但你沒有更新$scope.items。因此推送項目到$scope.items或者您可以創建後立即調用此代碼。它會更新你$ scope.items

foo.findAll().then(function (items) { 
       $scope.items = items; 
      }); 

使用此代碼:

.controller('FooCtrl', function($scope, $ionicPlatform, foo) { 
    $ionicPlatform.ready(function() { 
     foo.findAll().then(function (items) { 
      $scope.items = items; 
     }); 
    }); 

    $scope.item = {}; 
    $scope.addItem = function() { 
     foo.create({ name: $scope.item.name }); 
     $scope.items.push({ name: $scope.item.name }); 
    }; 
}) 

.controller('FooCtrl', function($scope, $ionicPlatform, foo) { 
    $ionicPlatform.ready(function() { 
     foo.findAll().then(function (items) { 
      $scope.items = items; 
     }); 
    }); 

    $scope.item = {}; 
    $scope.addItem = function() { 
     foo.create({ name: $scope.item.name }); 
      foo.findAll().then(function (items) { 
       $scope.items = items; 
      }); 
    }; 
}) 
+1

後一種解決方案應該通過創建一個'function fetchItems()'或類似的函數來進行DRY,以避免重複的代碼用於製作和處理API調用。 – DRobinson

+0

你是對的@DRobinson –

-1

這可能會解決這個問題:

foo.findAll().then(function (items) { 
      $scope.items = items; 
      $scope.$apply(); 
     }); 
+2

不要執行'$ apply','then'函數應該已經處於摘要循環中。 – DRobinson

+0

DRobinson是正確的 – jdobry

0

你是不是在任何地方存儲你的位指示創建的項目。我認爲foo.create返回一個項目,我是否正確?如果是這樣的話,也許是這樣的可以工作:

$scope.addItem = function() { 
    var item = foo.create({name: $scope.item.name}); 
    // this assumes that $scope.items is an array 
    $scope.items.push(item); 
}; 
0

如果您使用js-data-angular,那麼你也可以這樣做:

.controller('FooCtrl', function($scope, $ionicPlatform, foo) { 
    $ionicPlatform.ready(function() { 
    // retrieve that initial list of items 
    foo.findAll(); 

    // $scope.items will be kept up-to-date with 
    // the foo items in the store 
    foo.bindAll(null, $scope, 'items'); 
    }); 

    $scope.item = {}; 
    $scope.addItem = function() { 
    // thanks to the bindAll above, the 
    // created item will be rendered 
    // automatically 
    foo.create({ name: $scope.item.name }); 
    }; 
})