Skip to content

Instantly share code, notes, and snippets.

@byverdu
Last active June 1, 2017 00:12
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 byverdu/2fa298dd7415668345a6b29bd0ad909a to your computer and use it in GitHub Desktop.
Save byverdu/2fa298dd7415668345a6b29bd0ad909a to your computer and use it in GitHub Desktop.
// app/client/js/controllers/imdbController.js
module.exports = function( service, $routeParams, broadcaster, $rootScope, $timeout, Notification ) {
const $imdb = this;
$imdb.title = `${$routeParams.collection}`;
$imdb.collection = [];
$imdb.contentReady = false;
$imdb.singleItem = {};
$imdb.rating = 0;
$imdb.revealForm = false;
$rootScope.$on( 'item:searched', function ( event, item ) {
$timeout(() => {
$imdb.collection = item.data;
// A cada elemento de nuestra coleccion le añadimos la url donde
// podremos ver sus detalles, la idea es usar su "_id" como unico identificador
$imdb.collection = item.data;
angular.forEach( $imdb.collection, ( value, key ) => {
value.itemurl = `/imdb/${$routeParams.collection}/${value._id}`;
});
$imdb.singleItem = $imdb.collection.find( item => item._id === $routeParams.id );
$imdb.contentReady = true;
}, 500 );
});
service.getAPIData( $routeParams.collection )
.then( response => broadcaster.itemSearched( response ));
$imdb.deleteItem = function ( index ) {
// Pasamos el $index creado por ng-repeat para saber que _id tiene el
// elemento que queremos eliminar
const id = $imdb.collection[ index ]._id;
service.deleteItem( id )
.then(( resp ) => {
if ( resp.status === 200 ) {
Notification.success( `${resp.data}` );
$timeout(() => {
// En vez de volver a hacer un request a nuestra API
// como que sabemos que elemento estamos eliminando lo
// haremos directamente en la coleccion que ya tenemos :)
$imdb.collection.splice( index, 1 );
}, 500 );
} else {
Notification.error( 'Something went wrong deleting on DB' );
}
});
};
$imdb.showForm = function () {
$imdb.revealForm = true;
};
// Usaremos este metodo en la pagina de cada item de la coleccion
$imdb.updateItem = function () {
const id = $routeParams.id;
service.updateItem( id, $imdb.rating )
.then(( resp ) => {
if ( resp.status === 200 ) {
Notification.success( `${resp.data.data}` );
$imdb.singleItem = resp.data.movie;
$imdb.revealForm = false;
} else {
Notification.error( 'Something went wrong deleting on DB' );
}
});
};
};
// app/client/views/imdb.pug
block content
.wrapper(ng-controller="ImdbController as imdb")
div(ng-show="!imdb.contentReady") Loading ...
div(ng-show="imdb.contentReady")
h1 {{imdb.title}}
imdb-card(ng-repeat="imdbItem in imdb.collection", data="imdbItem", call-action="imdb.deleteItem( $index )" text-btn="Delete")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment