Skip to content

Expose a local state to views

Lucas Reis edited this page Mar 13, 2015 · 1 revision

Expose a local state variable to the views:

angular.module('myApp')
  .controller('FooCtrl', function($scope, AppState) {
  
  // declare the cursors to the
  // parts of the tree that will
  // be read or written in this
  // controller
  var foosCursor = AppState.select('foos');
  var barsCursor = AppState.select('bars');

  // this is the local state.
  // use .get to fill with
  // initial values
  var state = { 
    foos: foosCursor.get(),
    bars: barsCursor.get()
  };

  // update local state whenever 
  // the tree gets updated
  foosCursor.on('update', 
    function() { state.foos = foosCursor.get() });

  barsCursor.on('update', 
    function() { state.bars = barsCursor.get() });

 // example function that
 // manipulates tree
 var addFoo = function(newFoo) {
    foosCursor.push(newFoo);
  };

  // expose local state and
  // functions to views 
  $scope.state = state;
  $scope.addFoo = addFoo;
});