Created
February 28, 2017 22:20
-
-
Save hallboav/337b754efc76e339103f75cf4500f600 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<!DOCTYPE html> | |
<html ng-app="app"> | |
<head> | |
<meta charset="utf-8"> | |
<title>input-output-component</title> | |
</head> | |
<body> | |
<div ng-controller="AppController as appCtrl"> | |
<creature creature="appCtrl.creature" on-damage="appCtrl.notifyDamage(newHp, oldHp)" on-death="appCtrl.notifyDeath(name)"></creature> | |
</div> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script> | |
<script> | |
'use strict'; | |
(function (angular) { | |
angular | |
.module('app', ['creature']) | |
.controller('AppController', function ($log) { | |
this.creature = { name: 'Elf', hp: 100 }; | |
this.notifyDamage = function (newHp, oldHp) { | |
$log.info('Antes o life da criatura era ', oldHp, ' agora é ', newHp); | |
}; | |
this.notifyDeath = function (name) { | |
$log.info('A criatura ', name, ' morreu!'); | |
}; | |
}) | |
; | |
angular | |
.module('creature', []) | |
.component('creature', { | |
bindings: { | |
creature: '<', | |
onDamage: '&', | |
onDeath: '&' | |
}, | |
controller: function ($interval) { | |
var that = this; | |
this.damage = function (value) { | |
var oldHp = that.creature.hp; | |
var newHp = oldHp - value; | |
// O menor valor só pode ser zero | |
newHp = newHp < 0 ? 0 : newHp; | |
// Atualiza valor no objeto para atualizar a view | |
that.creature.hp = newHp; | |
// Notifica pros interessados que houve dano | |
that.onDamage({newHp: newHp, oldHp: oldHp}); | |
// Se criatura morreu | |
if (newHp === 0) { | |
// Notifica pros interessados que houve morte | |
that.onDeath({name: that.creature.name}); | |
// Cancela o timer que dá damage na criatura | |
$interval.cancel(that.timer); | |
} | |
}; | |
this.timer = $interval(function () { | |
// Gera um valor aleatório de no máximo 20, que será o dano na criatura | |
var rand = Math.floor(Math.random() * 20); | |
that.damage(rand); | |
}, 2000); | |
}, | |
template: | |
'<div><span>{{$ctrl.creature.name}}</span> (' + | |
'<span ng-if="$ctrl.creature.hp > 0">{{$ctrl.creature.hp}}</span>' + | |
'<span ng-if="$ctrl.creature.hp === 0">Morreu!</span>' + | |
')</div>' | |
, | |
}) | |
; | |
})(window.angular); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment