简体   繁体   English

角度范围变量在视图中未更新

[英]angular scope variable not updated in view

Beginners' angular question. 初学者的角度问题。 Probably. 大概。

Why does 为什么

//1
function setValue(target, value) {
    target = value;
}
setValue($scope.var1, 25);

not work, but 不起作用,但是

//2
function setValue(target, value) {
    $scope[target] = value;
}
setValue("var1", 25);

does? 有吗

The code's inside a controller. 代码在控制器内部。 I'm trying to make my code more modular but I frown upon passing a variable as a string instead of as a reference. 我试图使我的代码更具模块化,但是当我将变量作为字符串而不是作为引用传递时,我皱着眉头。 I've tried adding a $scope.$apply() to the former, as was suggested to me elsewhere, but that's throwing an error here. 我尝试在前者中添加一个$scope.$apply() ,就像在其他地方向我建议的那样,但这在这里引发了错误。

Many thanks 非常感谢

Angularjs updates it's view when the value of $scope changes. $scope的值更改时,Angularjs会更新其视图。

So according to your first code block 因此,根据您的第一个代码块

function setValue(target, value) {
    target = value; 
}
setValue($scope.var1, 25);

Because $scope.var1 is a string so here it will be passed by value, & when you are updating the target variable $scope remains same, that's why it's not being changed. 因为$scope.var1是一个字符串,所以这里将按值传递它,并且在更新目标变量$scope保持不变,这就是为什么它没有被更改的原因。

In your second codeblock 在第二个代码块中

function setValue(target, value) {
    $scope[target] = value;
}
setValue("var1", 25);

Here you are directly changing $scope so view is being updated. 在这里,您直接更改$scope以便更新视图。

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

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