Angularjs: 对象 属性 值未更新
Angularjs: Object property value does not update
我知道有多个问题与我的问题相关,但我仍然无法解决这个问题。我有以下 html 和 JavaScript 代码:
<!doctype html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
</head>
<body ng-controller="AppController">
<input type="" name="" ng-model="docs[1].value">
{{m3.value}}
{{m4}}
<script type="text/javascript">
var app = angular.module('Demo', []);
app.controller(
"AppController",
function( $scope ) {
$scope.docs=[{value:"first doc"}, {value:"second doc"}];
$scope.m3=$scope.docs[1];
$scope.m4=$scope.docs[1].value;
}
);
</script>
</body>
</html>
当我输入时,m3.value
得到更新,但 m4
没有!我不明白为什么会这样。任何评论表示赞赏。
语句 1:
$scope.m3=$scope.docs[1];
此语句存储模型的引用 docs[1]
因此,{{m3.value}}
将获得更新的模型值。
语句 2 :
$scope.m4=$scope.docs[1].value;
此语句复制实际原始值。
所以,{{m4}}
仍然得到旧值
好的,所以我解决它的方法是向 m3.value 添加一个观察者:
$scope.$watch('m3.value', function(){
console.log('Changing');
$scope.m4 = $scope.m3.value;
});
现在 $scope.m4 更新。
我知道有多个问题与我的问题相关,但我仍然无法解决这个问题。我有以下 html 和 JavaScript 代码:
<!doctype html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
</head>
<body ng-controller="AppController">
<input type="" name="" ng-model="docs[1].value">
{{m3.value}}
{{m4}}
<script type="text/javascript">
var app = angular.module('Demo', []);
app.controller(
"AppController",
function( $scope ) {
$scope.docs=[{value:"first doc"}, {value:"second doc"}];
$scope.m3=$scope.docs[1];
$scope.m4=$scope.docs[1].value;
}
);
</script>
</body>
</html>
当我输入时,m3.value
得到更新,但 m4
没有!我不明白为什么会这样。任何评论表示赞赏。
语句 1:
$scope.m3=$scope.docs[1];
此语句存储模型的引用 docs[1]
因此,{{m3.value}}
将获得更新的模型值。
语句 2 :
$scope.m4=$scope.docs[1].value;
此语句复制实际原始值。
所以,{{m4}}
仍然得到旧值
好的,所以我解决它的方法是向 m3.value 添加一个观察者:
$scope.$watch('m3.value', function(){
console.log('Changing');
$scope.m4 = $scope.m3.value;
});
现在 $scope.m4 更新。