我有一个接受输入的简单表单并将其添加到数组中。当它只是一个数组并且视图已更新时,这很好。
然而,当我创建两个数组时,每个数组都有自己的数组并更新内部数组,视图不会更新。
为什么会发生这种情况,我该如何解决?
以下是观点:
<div ng-app="test" ng-controller="TestController">
<div ng-repeat="group in groups">
<form ng-submit="submit($index)" ng-controller="TestController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text"/>
<input type="submit" id="submit" value="Submit"/>
<pre>list={% verbatim %}{{ list }}{% endverbatim %}</pre>
<pre>group.people={% verbatim %}{{ group.people }}{% endverbatim %}</pre>
</form>
</div>
</div>
这是控制器:
(function () {
// small groups application module
var testApp = angular.module('test', []);
testApp.controller('TestController', [
'$http',
'$scope',
function ($http, $scope) {
$scope.groups = [];
$scope.list = [];
$scope.text = 'hello';
for (var ii = 0; ii < 2; ii++) {
var group = {};
group.people = [];
$scope.groups.push(group);
}
$scope.submit = function (groupId) {
$scope.list.push($scope.text);
$scope.groups[groupId].people.push($scope.text);
console.debug($scope.groups[groupId].people);
$scope.text = '';
};
}]);
})();
非常感谢您的帮助。
解决。谢谢您的帮助。这是解决方案。
对于视图,只使用控制器的一个实例,并使用form.text作为ngmodel。
<div ng-app="test" ng-controller="TestController">
<div ng-repeat="group in groups">
<div ng-repeat="person in group.people">
{% verbatim %}{{ person }}{% endverbatim %}
</div>
<form ng-submit="submit($index)">
Enter text and hit enter:
<input type="text" ng-model="form.text" name="text">
<input type="submit" id="submit" value="Submit">
</form>
<pre>list={% verbatim %}{{ list }}{% endverbatim %}</pre>
<pre>group.people={% verbatim %}{{ group.people }}{% endverbatim %}</pre>
</div>
</div>
对于控制器,只需更新以使用$ scope.form.text。
$scope.groups = [];
$scope.list = [];
$scope.form = {};
$scope.form.text = 'hello';
for (var ii = 0; ii < 2; ii++) {
var group = {};
group.people = [];
$scope.groups.push(group);
}
$scope.submit = function (groupId) {
$scope.list.push($scope.form.text);
$scope.groups[groupId].people.push($scope.form.text);
console.debug($scope.groups[groupId].people);
$scope.form.text = '';
};
谢谢!