所以,现在我正在通过创建某种轻文本浏览器游戏来练习 JS/OOP/Angular :) 陷入了简单的情况(像往常一样)。我简化了我的代码,这里是:https://jsfiddle.net/gjgjc3fx/1/ 。所以我刚刚使用工厂创建了一个“类”英雄:
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;
})
然后在 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>
问题是 - 如果我想在 <div>{{currentDamage}}</div>
中看到我应该解决什么问题实时改变伤害?我的意思是,如果我点击按钮,它会增加 50 点伤害,并且我可以在警报窗口中看到变化,但是 <div>{{currentDamage}}</div>
始终保持不变(70)。任何帮助和建议都会很棒。
最佳答案
问题是您没有更新$scope.currentDemage
。要更新 $scope.currentDemage
,您必须从 Hero
Factory 获取 valuee。
在工厂中添加 getDamage
函数,例如
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;
}
}
将工厂实例分配给 ngController 中的 $scope
变量,例如
$scope.myService = am;
// watch getDamage() function for binding new Value.
$scope.$watch('myService.getDamage()',function(newvalue){
$scope.currentDamage = newvalue;
})
关于javascript - 实时显示变化的值(Angular、JS、OOP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40739622/