Eduardo Vendruscolo
Eduardo Vendruscolo

Reputation: 47

Ionic data synchronization between screen and controller

i'm beginner on ionic framework, i'm passing for problem with data synchronization, the interface call a function on controller, this function remove a item of a array lupulos, which is vinculed by angular ng-repeat="lupulo in lupulos", but, when a list of a item it's removed of a local database with success, it's made a spllice to remove a item from lupulos, the item is removed from controlller, but in the screen, the record still there, it's only disappear when i make some interaction in a screen, click in another item of a list, or leave the screen and return for example. how i make this refresh automatically? it was no longer to operate automatically?

sellAppCtrl.controller('LupuloCtrl', function ($scope, $location, $ionicPlatform, $ionicPopup) {

//list of records
$scope.lupulos = [];

//Delete record when confirmed pop up   
$scope.deleteLupulo = function (lupulo) {

    var confirmPopup = $ionicPopup.confirm({
        title: 'Remoção de lúpulo',
        template: 'Are you sure you want to delete hop ' + lupulo.nomelupulo + '?'
    });

    confirmPopup.then(function (res) {
        if (res) {
            //Deleta o objeto, passando o DOC como parametro.
            beerDb.remove(lupulo, function (err, response) {
                if (err) {
                    return console.log(err);
                }
                console.log(response);
                //when record whas success removed from database, remove from list too
                $scope.lupulos.splice($scope.lupulos.indexOf(lupulo), 1);
            });
        } else {

        }
    });

}

$ionicPlatform.ready(function () {
    //Retrieve data from de local database
    $scope.retrieveLupulos();
});

});

database is on the app.js

var sellApp = angular.module('starter', ['ionic', 'angular-datepicker', 'starter.controllers']);
var beerDb = new PouchDB("beer");

sellApp.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        if (window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
})

Upvotes: 0

Views: 393

Answers (2)

Brian
Brian

Reputation: 903

You need to use $scope.$apply() to inform the view it needs to update:

$scope.$apply(function(){
    $scope.lupulos.splice($scope.lupulos.indexOf(lupulo), 1);
});

Upvotes: 0

yazaki
yazaki

Reputation: 1632

You need to wrap your splice function call by $scope.$apply to update view.

The code will be like below.

$scope.$apply(function(){
    $scope.lupulos.splice(...
});

The reason why you need to wrap it by $scope.$apply is that angularjs doesn't support the asynchronous callback function of 3rd party library(for instance jquery ajax callback function) to update view automatically. If you use angularjs service(for instance $http, $resource...), you don't need to do this.

Official document is here

Upvotes: 0

Related Questions