繁体   English   中英

如何使ng-init触发ng-change?

[英]How can I make ng-init to trigger ng-change?

我刚开始学习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()函数,因为在所选模型和输入字段之间已经存在双向绑定设置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM