2015-04-22 36 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 }); 
    }; 
}) 
相关问题