gpt4 book ai didi

javascript - AngularJS 数据绑定(bind)单个值到两个变量。第二个变量未在 View 中更新

转载 作者:行者123 更新时间:2023-11-29 18:04:38 25 4
gpt4 key购买 nike

我有一个文本框,其值绑定(bind)到我的 Controller 中的 $scope.stringOne。然后我有第二个变量,$scope.stringTwo,它是 stringOne 和更多文本的串联。

但是,当我在文本框中键入时,stringOne 在 View 中成功更新,但 stringTwo 保持不变。

为了让 stringTwo 的值在 stringOne 更新时也更新,还需要什么来使它工作?

HTML

<body ng-controller="mainCtrl">
<div class="container">
<label>Enter Text</label>
<input type="text" ng-model="stringOne"/>
<h1>{{stringOne}}</h1>
<h1>{{stringTwo}}</h1>
</div>
</body>

JS

var myApp = angular.module('myApp',[]);

myApp.controller('mainCtrl',['$scope',function ($scope,) {

$scope.stringOne = '';
$scope.stringTwo = $scope.stringOne + ' more texts';

}]);

最佳答案

使用 $watch

var myApp = angular.module('myApp',[]);

myApp.controller('mainCtrl',['$scope',function ($scope,) {

$scope.stringOne = '';
$scope.$watch('stringOne', function(new_value){
$scope.stringTwo = new_value + ' more texts';
});
}]);

官方docs
关于 watch 的有用帖子


为什么会这样

当您初始化 $scope.stringOne 时,它会收到空字符串,当您将它添加到 html ng-model 属性中时,它基本上会监视该变量的变化,但是 $scope.stringTwo 你需要自己看

关于javascript - AngularJS 数据绑定(bind)单个值到两个变量。第二个变量未在 View 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32288019/

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