简体   繁体   English

变量引用对象的值,但在对象出现时不会更新

[英]variable references an object's value, but is not updated when the object is

I'm testing out Angular.js (quite enjoying it), but this might be more of a pure js question in fact. 我正在测试Angular.js(非常喜欢它),但事实上这可能更像是一个纯粹的问题。

The exercise scenario is that I have two matches: 练习场景是我有两场比赛:

  • Player A vs. Player B 玩家A与玩家B
  • The winner of the first match (Player A or B) vs. Player C 第一场比赛(球员A或B)与球员C的胜者

Here I am representing the first match: 我在这里代表第一场比赛:

$scope.match1 = {
   p1: "Player A",
   p2: "Player B",
   winner: "to be determined"
};

When I set up the second match, I declare a variable with a reference to the match 1 winner, as such: 当我设置第二场比赛时,我声明一个变量,其中包含对比赛1获胜者的引用 ,如下:

$scope.match2 = {
   p1: $scope.match1.winner,
   p2: "Player C",
   winner: "tbd"
};

Now I have a button click which assigns a winner to match 1, but THIS VALUE IS NOT PASSED to match 2 (match2.p1 value remains "to be determined" although it references match1.winner which is now updated). 现在我有一个按钮点击,它指定一个赢家匹配1,但是这个值没有通过匹配2(match2.p1值保持“待确定”,尽管它引用了match1.winner,现在更新)。

What gives? 是什么赋予了? Thanks in advance for any help or contribution! 在此先感谢您的帮助或贡献!

Here is a fiddle to play with: http://jsfiddle.net/legolandbridge/mAjX5/2/ 这是一个小提琴: http//jsfiddle.net/legolandbridge/mAjX5/2/

That is because your winner field is a string not an object . 这是因为您的winner字段是字符串而不是object And you cannot get a reference to String. 而你无法获得String的引用。 That will be value. 这将是价值。

Have winner field as an object so when you will change your winner 's value it will be changed in match2 also. winner字段作为object因此当您更改winner者的值时,它也将在match2更改。

Try something like bellow. 尝试像波纹管一样的东西。

function AppCtrl($scope) {
    $scope.match1 = { // p1 vs p2 
       p1: "Player A",
       p2: "Player B",
        winner: {name:"to be determined"} //Object
    };
    $scope.match2 = {
       p1: $scope.match1.winner, // an reference to winner of match one
       p2: "Player C",
       winner: "to be determined"
    };

    $scope.getWinner = function() { //on click
        $scope.match1.winner.name = "Player B"; 
        console.log($scope.match2.p1); //value is updated
    };


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM