[SOLVED] localStorage and $scope binding


#1

Friends,

in my controller I have exactly this:

   .controller('JornadaCtrl', function($scope) {
    var getJornada = function(){
        if (!localStorage.Horas){
            localStorage.Horas = 8;
        }

        return parseInt(localStorage.Horas);
            
    }
    
    $scope.qtdeHoras = getJornada();
    
    $scope.salvar = function(){
        localStorage.Horas = $scope.qtdeHoras;
        alert($scope.qtdeHoras);
    }
   
})

As you can see, I have a property “qtdeHoras”, receiving value from getJornada function. In My view, this property “qtdeHoras” is bind to an input, like this:

<input type="number" ng-model="qtdeHoras"> <br/>
<tt> Value = {{qtdeHoras}}</tt>  

In the View, everything is OK, as value get changed in the input, the tt is updated. BUT, I also have a button triggering my “salvar()” function. If you look into it, you see I’m using an alert to display “qtdeHoras” value…and here is the problem.

When I open this view, “qtdeHoras” is “5”, so I change it to “8”. Binding shows this correctly, but when I click my button, is shown the first value “5”, not the “8”…

I can’t see what is wrong here… :frowning:


#2

It’s hard to say for sure without a working sample.

However, I think you are running into a common problem. $scope.qtdgeHoras = getJornada is setting a “primitive”. It’s a simple value. When Angular binds the scope to the view, it uses “prototypal inheritance”. Because $scope.qtdeHoras is a primitive, it simply copies into the view. The view will update, but the $scope will not.

To avoid this, you need to use “dot notation”. Basically, it means assigning the model in your scope to a complex object like an array or object, rather than a primitive.

So, something like this:

 .controller('JornadaCtrl', function($scope) {
    $scope.data = {}; // Creates an object

    var getJornada = function(){
        if (!localStorage.Horas){
            localStorage.Horas = 8;
        }

        return parseInt(localStorage.Horas);

    }

    $scope.data.qtdeHoras = getJornada();

    $scope.salvar = function(){
        localStorage.Horas = $scope.data.qtdeHoras;
        alert($scope.data.qtdeHoras);
    }

})

FYI : Read this excellent explanation to understand this better. https://github.com/angular/angular.js/wiki/Understanding-Scopes


#3

My friend, you are completely right!!! Thank you!!!