简体   繁体   中英

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.

Many thanks

Angularjs updates it's view when the value of $scope changes.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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