grevory / angular-local-storage

An AngularJS module that gives you access to the browsers local storage with cookie fallback
Other
2.83k stars 585 forks source link

Using bind with controllers that use controllerAs syntax #170

Open chrissearle opened 9 years ago

chrissearle commented 9 years ago

Not sure what to send in as scope when using controllers that are set up with controllerAs syntax (that is with all properties etc on "this"). Any pointers?

bluedaniel commented 9 years ago

+1

jacekd commented 9 years ago

+1

GabrielGil commented 9 years ago

+1

jouke commented 9 years ago

+1

GabrielGil commented 9 years ago

Hello y'all!! That's another practical example done with a localstorage implementation done "the right way" for angular. Exactly with the binding you are talking about but done properly. Here a working example with a "Cart" and "Product" controllers and a CartService for holding the data. Within the controller would be all right as well. Give it a try... It even synchronizes between open tabs. http://codepen.io/GabrielGil/pen/VYExZv

levivm commented 9 years ago

+1

patlux commented 9 years ago

+1

rebelliard commented 9 years ago

My solution: Given a { model: { id: 1, name: 'foo' } } structure:

angular.controller('StoreSearchController', function($scope, localStorageService) {
  var vm = this;

  var localStorageKey = 'store';
  vm.model = localStorageService.get(localStorageKey) || {};
  localStorageService.bind($scope, 'vm', vm.model, localStorageKey);

  $scope.$watchCollection(function () {
    return vm.model;
  }, function(model) {
    // Bind the view model's value to the $scope, 
    // so the storage service can catch it.   
    $scope.vm = model;
  });
});

Tested on version 0.2.0.