[英]AngularJS: Changing object does not update field but changing string directly does
I feel like this is something trivial, but I've been stuck for awhile. 我觉得这很琐碎,但是我已经坚持了一段时间。
I have an object user
, set in the directive UserSettings. 我有一个对象
user
,在指令UserSettings中设置。 The directive's element contains a button with html {{user.name}}
to open a model for user settings. 指令的元素包含带有html
{{user.name}}
的按钮,用于打开用于用户设置的模型。 When the page loads user.name
is set. 页面加载时设置了
user.name
。
The user settings form in the modal is contained by a controller called UserSettingsForm. 模态中的用户设置表单包含在名为UserSettingsForm的控制器中。 I've been trying to debug the controller and I'm confused by the behavior I'm seeing.
我一直在尝试调试控制器,但我对所看到的行为感到困惑。
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
The above debugging works as expected, but the unexpected part (for me, at least) is the fact that {{user.name}}
in the nav bar is not being updated. 上面的调试工作按预期进行,但是意外的部分(至少对我来说)是导航栏中的
{{user.name}}
未得到更新的事实。 But when I do @$scope.user.name = @$scope.test.name
the {{user.name}}
field in the HTML is updated. 但是,当我执行
@$scope.user.name = @$scope.test.name
时,HTML中的{{user.name}}
字段将更新。
I am admittedly an angular noob (even though this is probably a JavaScript concept), but the logic I'm having trouble with doesn't make sense to me and I would be very appreciative if someone could clear it up for me, and maybe even give me a push in the right direction as far as properly updating the user
object to equal the test
object. 我确实是一个有角的菜鸟(即使这可能是一个JavaScript概念),但是我遇到的逻辑对我来说没有意义,如果有人可以为我清除它,我将不胜感激,也许甚至在正确方向上推动我,以正确地更新
user
对象以使其等于test
对象。 test
will eventually be an instance of the user settings form and only when the data is saved successfully will that instance be saved as user
. test
最终将成为用户设置表单的一个实例,只有成功保存数据后,该实例才会保存为user
。
Angular is still watching the previous reference, even after you do the change. 即使您进行更改,Angular仍在监视先前的参考。
If you use: 如果您使用:
angular.copy(source, destination)
It will deleted all of the previous properties and replace them with the source properties. 它将删除所有先前的属性,并将其替换为源属性。
Here's the updated example for your case: 这是您的案例的更新示例:
angular.copy($scope.test, $scope.user)
That statement should solve the issue. 该声明应解决该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.