gpt4 book ai didi

angularjs - ngModel 与 ngSwitch,无法监视字符串变量?

转载 作者:行者123 更新时间:2023-12-02 22:21:34 24 4
gpt4 key购买 nike

我在使用 $scope.$watch 时遇到问题关于我项目范围内的一些 Angular 变量。我做了一个样本jsfiddle来说明问题。

基本上我可以$scope.$watch ng-switch 内的任何型号只要它是一个物体。如果它是一个字符串,它将不会触发监视表达式,并且不会在 ng-switch 的范围之外进行更改。区域。 Angular 是否复制原始字符串而不是像对象一样通过引用传递它?

我正在使用 ng-repeat在一些元素上——这是我的一些代码:

<div ng-switch="key">

<div ng-switch-when="deal_id">
DEALID: <input type="text" ng-model="dealIdModel"/> -- {{dealIdModel}}
</div>
<div ng-switch-when="thing_id">
THING: <input type="text" ng-model="thingIdModel.test"/> -- {{thingIdModel.test}}
</div>
<div ng-switch-default>
DEFAULT: <input type="text" placeholder="email" ng-model="items.params.email"/> -- {{items.params.email}}
</div>

</div>

还有 JS:

$scope.items = {
"statusCode":"ACTIVE",
"params":{
"deal_id":"",
"thing_id":"",
"email":"Change me! I will get called"
}
};

$scope.dealIdModel = "I won't change outside of the loop or get called.";
$scope.thingIdModel = {test:'Change me! So will I!'};

$scope.$watch('items.params.email', function (now, then, scope) {
console.log('email change', now, then);
});

$scope.$watch('thingIdModel.test', function(now, then, scope) {
console.log('changed the thing', now, then);
});

$scope.$watch('dealIdModel', function(now, then, scope) {
console.log('dealID changed:', now, then);
});

最佳答案

这与 ng-repeat 创建的子作用域有关。由于创建了一个新作用域,如果您在子作用域上设置一个普通变量,您将更改那里的引用,但不会更改父作用域中的引用。当您使用对象时,父级会维护对该对象的引用,并且只有内部部分会发生变化。

这与您听到“始终在您的 ng-model 中加点”时遇到的问题相同

这里有更多详细信息: https://github.com/angular/angular.js/wiki/Understanding-Scopes

关于angularjs - ngModel 与 ngSwitch,无法监视字符串变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29682210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com