我有一个变量,我想在另一个作用域改变它的值时改变它。
$scope.switch = true;
var thing;
if ($scope.switch == false) {
thing = "givesFalse";
}
else {
thing = "givesTrue";
};
this.thingscope = thing;
因此,当我将 $scope.switch
值更改为 false 时,this.thingscope
应该输出 givesFalse
。为了更改范围值,我使用 ng-click:
<div ng-controller="myCtrl as myCtrl" ng-app="myApp">
{{myCtrl.thingscope}}
<br>
<a ng-click="switch = !switch">{{switch}}</a>
</div>
但即使我可以看到范围确实更新了,变量 thing
似乎并没有同时更新。您可以看到工作插件 here .提前致谢!
最佳答案
你有两个选择:
0 - 自动:使用 watch
$scope.$watch('switch', function () {
$scope.thing = $scope.switch ? "givesTrue" : "givesFalse";
});
1 - 手动:使用更改两个值的自定义函数。
ng-click="switch = !switch"
将其更改为:
ng-click="customFunction()"
并在 Controller 中定义:
$scope.customFunction = function () {
$scope.switch = !$scope.switch;
$scope.thing = $scope.switch ? "givesTrue" : "givesFalse";
}
关于javascript - AngularJS - 在范围更改时使用 if else 语句更改变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642549/