带数组的 ngModel
ngModel with Arrays
我正在尝试将我的(在其他地方定义的)变量组织到一个数组中,但这会破坏双向绑定。我不明白为什么我可以直接绑定到一个变量,而不是间接绑定。我猜这是一些愚蠢的错误。
示例 here (jsfiddle) 或以下:
Html:
<div ng-controller="MyCtrl">
<input ng-model="test1"></input>
<input ng-model="test2[0]"></input>
<p>{{test1}}</p>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.test1 = 'text goes here';
$scope.test2 = [$scope.test1];
}
如您所见,第一个输入绑定到变量并正确更新它,而第二个输入采用初始值,但未绑定。
它确实有效。参见 https://jsfiddle.net/ryekxkpL/2/
$scope.test2[0]
是 $scope.test1
的副本,所以它与您 $scope.test2 = ['text goes here'];
相同,更改它不会影响 $scope.test1
。
我正在尝试将我的(在其他地方定义的)变量组织到一个数组中,但这会破坏双向绑定。我不明白为什么我可以直接绑定到一个变量,而不是间接绑定。我猜这是一些愚蠢的错误。 示例 here (jsfiddle) 或以下:
Html:
<div ng-controller="MyCtrl">
<input ng-model="test1"></input>
<input ng-model="test2[0]"></input>
<p>{{test1}}</p>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.test1 = 'text goes here';
$scope.test2 = [$scope.test1];
}
如您所见,第一个输入绑定到变量并正确更新它,而第二个输入采用初始值,但未绑定。
它确实有效。参见 https://jsfiddle.net/ryekxkpL/2/
$scope.test2[0]
是 $scope.test1
的副本,所以它与您 $scope.test2 = ['text goes here'];
相同,更改它不会影响 $scope.test1
。