我刚开始学习Angular.有一个< select>应该用一些礼物填充下面的输入元素的元素.
这是我的观点.
<select ng-model="selection" ng-options="preset.name for preset in presets" ng-init="selection=presets[0]" ng-change="select()"></select> <input ng-model="name" type="text"/> <textarea ng-model="description"></textarea>
这是我的控制器.
$scope.presets = [ { name: 'Lorem ipsum',description: 'Dolor sit amet.' },{ name: 'Consectetur',description: 'Adipisicing elit.' },{ name: 'Sed do',description: 'Eiusmod tempor.' },]; $scope.select = function() { $scope.name = $scope.selection.name; $scope.description = $scope.selection.description; };
当我加载页面时,我可以看到选择的第一个选项.但是在我手动更改选择之前,输入字段仍为空白.为什么Angular不首先自动设置输入字段,我该怎么办呢?
解决方法
它最初没有设置文本字段的原因是因为在调用select()之前没有$scope.name和$scope.description的绑定设置.您最初可以在控制器功能中进行设置:
$scope.init = function(selected) { $scope.selection = selected; $scope.name = $scope.selection.name; $scope.description = $scope.selection.description; } $scope.select = function() { $scope.name = $scope.selection.name; $scope.description = $scope.selection.description; };
在你的HTML中:
<select ng-model="selection" ng-options="preset.name for preset in presets" ng-init="init(presets[0])" ng-change="select()"></select>
替代方法:
或者,您可以将输入字段绑定到相同的选择模型.那样,
当在范围上更新选择模型时,它将更新所有关联的视图.
将模型更改为’selection.name’和’selection.description’:
<input ng-model="selection.name" type="text"/> <textarea ng-model="selection.description"></textarea>
不再需要select()函数,因为在所选模型和输入字段之间已经存在双向绑定设置.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。