Bob & Ash
angular.module('starter')
.config(appConfig);
appConfig.$inject = ['$ngReduxProvider', 'rootReducerProvider'];
function appConfig($ngReduxProvider, rootReducerProvider) {
$ngReduxProvider.createStoreWith(rootReducerProvider.$get(), [
'promiseMiddleware',
'loggerMiddleware'
]);
}
angular.module('starter')
.factory('rootReducer', rootReducer);
rootReducer.$inject = ['phonesReducer'];
function rootReducer(phonesReducer) {
return Redux.combineReducers({
phones: phonesReducer
});
}
...
function reducer(state, action) {
var initialState = {
phones: []
};
if (angular.isUndefined(state)) {
return angular.copy(initialState);
}
switch (action.type) {
case 'CREATE_PHONE':
state.phones.push(action.payload);
break;
case 'SET_PHONES_FULFILLED' :
state = angular.copy(action.payload);
break;
}
return state;
}
...
function PhonesController($scope, $ngRedux) {
var vm = this;
var unsubscribe = $ngRedux.connect(mapStateToVm)(vm);
$scope.$on('$destroy', unsubscribe);
function mapStateToVm(state) {
return {
phones: state.phones
};
}
}
...
function phonesActions(phonesService) {
return {
createPhone: createPhone,
setPhones: setPhones
};
function createPhone(phone) {
return {
type: 'CREATE_PHONE',
payload: phone
};
}
function setPhones() {
return {
type: 'SET_PHONES',
payload: {
promise: phonesService.getPhones()
}
};
}
}
...
function PhonesController($scope, $ngRedux, phonesActions) {
var vm = this;
var unsubscribe = $ngRedux.connect(mapStateToVm, phonesActions)(vm);
vm.onSubmit = onSubmit;
$scope.$on('$destroy', unsubscribe);
vm.setPhones();
function mapStateToVm(state) {
return {
phones: state.phones
};
}
function onSubmit(phone) {
vm.createPhone(phone);
}
}
<h1 ng-bind="vm.title"></h1>
<form name="phoneCreateForm" ng-submit="vm.onSubmit(vm.newPhone)">
<input type="text" name="title" autocomplete="off" ng-model="vm.newPhone"/>
<button type="submit">Create phone</button>
</form>
<ul>
<li ng-repeat="phone in vm.phones" ng-bind="phone"></li>
</ul>
function thunkMiddleware(store) {
return function (next) {
return function (action) {
if (typeof action === 'function') {
return action(store.dispatch, store.getState);
}
return next(action);
};
};
}