Created
April 3, 2015 09:24
-
-
Save aantipov/87c4a030ee1406610313 to your computer and use it in GitHub Desktop.
An example of angular.js controller written in CoffeeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
Dialogs Controller | |
@author Alexei Antipov <[email protected]> | |
### | |
define [], () -> | |
'use strict' | |
class DialogsCtrl | |
_services = {} | |
_itemsDeferred = no | |
_limit = 20 # Items per page | |
constructor: (args...) -> | |
_services = _.object(DialogsCtrl.$inject, args) | |
# Init variables, exported to the view | |
@items = [] # Dialogs list | |
@total = 0 # Total number of dialogs | |
@pattern = '' # Search input | |
@active = no # Active dialog | |
@isLoading = on # The state of dialogs loading | |
# Get the first portion of dialogs | |
do @_getItems | |
# Search dialogs # | |
search: -> | |
@items.length = 0 | |
do @closeMessages | |
do @_getItems | |
# Get next portion of dialogs # | |
getItems: -> | |
return if @isLoading | |
do @_getItems | |
# Load dialog messages # | |
loadMessages: (dialog) -> | |
@active = dialog.id | |
dialog = _.find(@items, {id: dialog.id}) | |
dialog && dialog.new_messages_count = 0 # Mark messages as read. | |
_services.$state.go 'index.dialog.id', {id: dialog.id} | |
# Close dialog messages list # | |
closeMessages: -> | |
@active = no | |
_services.$state.go 'index.dialog' | |
# Private method to get dialogs data # | |
_getItems: -> | |
_itemsDeferred and _itemsDeferred.reject(no) # Cancel current request if any | |
_itemsDeferred = _services.$q.defer() # And create new request | |
defer = _itemsDeferred | |
@isLoading = on | |
_services.dialogsApi.getItems {count: _limit, start: @items.length, pattern: @pattern} | |
.then (data) => | |
defer.resolve(data) | |
.catch (error) -> | |
defer.reject(error) | |
defer.promise | |
.then (data) => | |
@total = data.total | |
@items = @items.concat data.dialogs | |
@isLoading = no | |
data | |
DialogsCtrl.$inject = ['$q', '$state', '$log', 'dialogsApi'] | |
DialogsCtrl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment