请看下面的代码。
为什么在输入字段中插入有效值时 $scope.data
变量不更新?
我怎样才能做到这一点?
代码笔:http://codepen.io/uloco/pen/jboorN
HTML
<div ng-app="app" ng-controller="AppController" class="content">
<input type="tel" ng-model="form.phone" placeholder="phone" />
<input type="email" ng-model="form.email" placeholder="email" />
<p>{{form}}</p>
<p>{{data}}</p>
</div>
JS
angular
.module('app', [])
.controller('AppController', function($scope) {
$scope.form = {};
$scope.data = {
foo: 'bar',
phone: $scope.form.phone,
email: $scope.form.email
}
});
最佳答案
Why does the $scope.data variable not update?
因为$scope.data
和$scope.form
之间没有联系。这是两个具有独立属性的独立对象,您正在更改 $scope.form
的属性。
如果你真的想要两个单独的对象,你需要手动同步它们,或者使用 $scope.form< 上的
$scope.$watch
/
$scope.$watch('form', function(obj) {
$scope.data.phone = obj.phone;
$scope.data.email = obj.email;
}, true);
演示:http://codepen.io/anon/pen/PPvvBr?editors=101
或使用 ngChange
指令:
<input type="tel" ng-model="form.phone" placeholder="phone" ng-change="sync()" />
<input type="email" ng-model="form.email" placeholder="email" ng-change="sync()" />
和
$scope.sync = function() {
$scope.data.phone = $scope.form.phone;
$scope.data.email = $scope.form.email;
};
演示:http://codepen.io/anon/pen/bVyyQN?editors=101
在这种情况下,首选ngChange
解决方案。但是,如果您有 2 个以上的字段,那么 $watch 可能会更简单。
关于javascript - 通过 ng-model 更新不同的 $scope 对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33913022/