javascriptangularjsionic-frameworkjsdata

How to update my $scope after adding new elements?


I have a problem with my controller. I use ionic (angular) and js-data. when I add a new item via addItem() I will only when see it if I reload the page via F5.

Here is my code:

.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 });
    };
})

what I have to do to see the new element withous first pressing F5 in my browser window?


Solution

  • you are creating an item and updating database. but you are not updating $scope.items. so push item to $scope.items or you can call this code just after creating. it will update you $scope.items

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

    use this code:

    .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 });
        };
    })
    

    or

    .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;
                });
        };
    })