Skip to content

Instantly share code, notes, and snippets.

@aantipov
Created April 3, 2015 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aantipov/87c4a030ee1406610313 to your computer and use it in GitHub Desktop.
Save aantipov/87c4a030ee1406610313 to your computer and use it in GitHub Desktop.
An example of angular.js controller written in CoffeeScript
###
Dialogs Controller
@author Alexei Antipov <antipov.alexei@gmail.com>
###
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