Angular.js Service

by gkohen

HTML

<div ng-app="myApp">
  <div ng-controller="farmController">
    <button ng-click="buyCow()">Buy Cow</button>
    <button ng-click="stop()">Stop Farming</button>
    <div id="farm">
      <div class="grass" ng-repeat="g in grass">
        <img src="https://drive.google.com/uc?export=view&id=0B1mQfOwV0VUHWWhiRmM5bVlIczA" />
      </div>
      <div class="cow" ng-repeat="c in cows">
        <img src="https://drive.google.com/uc?export=view&id=0B1mQfOwV0VUHdTdBdHBibVM0UGM" />
      </div>
      <br style="clear:both" />
    </div>
  </div>
</div>

CSS

#farm {
  width: 350px;
  height: 400px;
  border: 3px double wheat;
  padding: 10px;
}

.grass {
  float: left;
}

.cow {
  float: left;
}

Babel + JSX

import angular from 'angular';

var myApp = angular.module('myApp', []);

//Model
class Cow {
  constructor() {
    this.ateGrass = 0;
  }

  eatGrass() {
    var isAlive = false;
    if (this.ateGrass < 4) {
      this.ateGrass += 1;
      isAlive = true;
    }
    return isAlive;
  }
}

//Module(Service)
myApp.service('farmService', function() {
  this.ateGrassTotal = 0;
  this.evalFarm = function(times, cows) {
    var grass = times - this.ateGrassTotal;
    var newCows = [];
    for (var i = 0; i < cows.length; i++) {
      if (cows[i].eatGrass()) {
        grass -= 1;
        this.ateGrassTotal += 1;
        newCows.push(cows[i]);
      }
    }
    return {
      grass: grass,
      cows: newCows
    }
  };
});

//Controller
myApp.controller("farmController", function($scope, $timeout, farmService) {
  $scope.times = 0;
  $scope.grass = [];
  $scope.cows = [];
  $scope.onTimeout = function() {
    $scope.times += 1;
    var farm = farmService.evalFarm($scope.times, $scope.cows);
    $scope.grass = [];
    for (var i = 0; i < farm.grass; i++) {
      $scope.grass.push(i);
    }
    $scope.cows = farm.cows;
    myTimer = $timeout($scope.onTimeout, 1000);
  }
  var myTimer = $timeout($scope.onTimeout, 1000);
  $scope.stop = function() {
    $timeout.cancel(myTimer);
  }
  $scope.buyCow = function() {
    $scope.cows.push(new Cow());
  }
})