impregnable fiend impregnable fiend - 10 days ago 9
AngularJS Question

Display changing's value in real time (Angular, JS, OOP)

So, Right now I'm practicing JS/OOP/Angular via creating some kind of light-text-browser-game :) Got stuck in the simple situation (like always). I simplify my code a bit, here it is: https://jsfiddle.net/gjgjc3fx/1/. So I've just created a 'class' Hero using factory:

angular.module('myGame', [])
.factory('Hero', function() {
function Hero(name, damage) {
this.name = name;
this.damage = damage;
}
Hero.prototype = {
talk : function() {
alert('Hi, my name is: ' + this.name + ', my current damage is: ' + this.damage);
},
addDamage : function(damage) {
this.damage += damage;
console.log(this.damage);
}
}

return Hero;
})


and then use it in controller:

.controller('myGameCtrl', function($scope, Hero) {
var am = new Hero('AntiMage', 70);

$scope.currentDamage = am.damage;
$scope.hi = function() {
am.talk();
}
$scope.add50Dmg = function() {
am.addDamage(50);
}
})


HTML:

<div ng-app='myGame' ng-controller='myGameCtrl'>
<div>{{currentDamage}}</div>
<button ng-click='add50Dmg()'>Add 50 damage</button>
<div ng-click='hi()'>Hi</div>
</div>


The question is - what am I suppose to fix if I wanna see in the
<div>{{currentDamage}}</div>
changing damage in real time? I mean if I click on button it will add 50 damage and I can see change in alert's window, but the
<div>{{currentDamage}}</div>
stay the same (70) all the way. Any help and advices will be great.

Answer

your Updated fiddle

The problem is you are not updating $scope.currentDemage. For updating $scope.currentDemage you have to get the valuee from your Hero Factory.

Add getDamage function in your factory like

Hero.prototype = {
    talk : function() {
    alert('Hi, my name is: ' + this.name + ', my current damage is: ' + this.damage);
  },
  addDamage : function(damage) {
    this.damage += damage;
    console.log(this.damage);
  },

  /* getDamage function */
  getDamage : function(){
      return this.damage;
  }
}

Assign your factory instance to $scope variable in ngController like

 $scope.myService = am;

// watch getDamage() function for binding new Value.
$scope.$watch('myService.getDamage()',function(newvalue){
    $scope.currentDamage = newvalue;
})
Comments