繁体   English   中英

AngularJS:更改对象不会更新字段,但是直接更改字符串可以

[英]AngularJS: Changing object does not update field but changing string directly does

我觉得这很琐碎,但是我已经坚持了一段时间。

我有一个对象user ,在指令UserSettings中设置。 指令的元素包含带有html {{user.name}}的按钮,用于打开用于用户设置的模型。 页面加载时设置了user.name

模态中的用户设置表单包含在名为UserSettingsForm的控制器中。 我一直在尝试调试控制器,但我对所看到的行为感到困惑。

console.log @$scope.user # debug to show user object is there
@$scope.test = angular.copy(@$scope.user) # set test equal to a copy of user
@$scope.test.name = 'wowee' # change test object's 'name' property
@$scope.user = angular.copy(@$scope.test) # set user back to test
console.log @$scope.test # test is changed
console.log @$scope.user # user is equivalent to test

上面的调试工作按预期进行,但是意外的部分(至少对我来说)是导航栏中的{{user.name}}未得到更新的事实。 但是,当我执行@$scope.user.name = @$scope.test.name时,HTML中的{{user.name}}字段将更新。

我确实是一个有角的菜鸟(即使这可能是一个JavaScript概念),但是我遇到的逻辑对我来说没有意义,如果有人可以为我清除它,我将不胜感激,也许甚至在正确方向上推动我,以正确地更新user对象以使其等于test对象。 test最终将成为用户设置表单的一个实例,只有成功保存数据后,该实例才会保存为user

即使您进行更改,Angular仍在监视先前的参考。

如果您使用:

angular.copy(source, destination)

它将删除所有先前的属性,并将其替换为源属性。

这是您的案例的更新示例:

angular.copy($scope.test, $scope.user)

该声明应解决该问题。

暂无
暂无

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

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