angularjs-state-emitter

modify shared state through an message bus

Usage no npm install needed!

<script type="module">
  import angularjsStateEmitter from 'https://cdn.skypack.dev/angularjs-state-emitter';
</script>

README

angularjs-state-emitter


Use an event-based api similar to choo's to manage shared state in your Angular.js 1.x app.

Usage

1. Register angularjs-state-emitter as a dependency of your app:

var stateEmitter = require('angularjs-state-emitter')

angular.module('myApp', [stateEmitter])

2. Declare your store in a run block:

angular.run(store)

function store (state, emitter) {
  state.clicks = 0

  emitter.on('increment', function () {
    state.clicks += 1
    emitter.emit('render')
  })
}

3. Pass state down from your root component:

function ComponentCtrl (state) {
  var ctrl = this
  ctrl.state = state
}
<my-component state="$ctrl.state"></my-component>

it also works with @ui-router/angularjs:

$stateProvider.state({
  name: 'layout',
  component: 'myComponent',
});
<ui-view state="$ctrl.state"></ui-view>

4. Emit actions from any components

module.exports = {
  template: `<button ng-click="$ctrl.handleClick()">increment</button>`,
  bindings: { 
    state: '<' 
  },
  controller: function ButtonCtrl (emit) {
    var ctrl = this

    ctrl.handleClick = function () {
      emit('increment')
    }
  }
}

Installation

npm install angularjs-state-emitter

Logging

Enable logging through the $stateEmitterProvider in a config block:

function myConfig ($stateEmitterProvider) {
  $stateEmitterProvider.debug(true)
}

See also