如何简化 angular 中的 <select>

how to simplify the <select> in angular

我有一个包含这么多属性的 <select> 下拉列表,在 html 文件中查看它会很痛苦。使用 angular 将其重构为看起来更轻松的内容的最佳方法是什么?在控制器中设置它?也许是一个指令?

<select name="connection" id="connectionId" class="form-control"
    ng-init="selectedConnection = connections[0]"
    ng-change="onChangeConnection()"
    ng-model="selectedConnection"
    ng-options="connection for connection in connections"></select>

你可以删除 ng-init 并将初始化放在控制器中。

在控制器中你应该这样做 $scope.selectedConnection= connections[0] 模板中 ng-change 的替代方法是在与所选模型连接相关的控制器中放置 $watch

$scope.$watch('selectedConnection', function(newValue, oldValue){
    console.log("value changed")
}, true);

每次在模型中检测到变化时,$watch 中的函数都会调用。

你真的不需要 id,你当然不应该使用 ng-init - 应该在控制器中设置视图模型变量。

$scope.selectedConnection = $scope.connections[0]

如果您打算对此 <select> 上的验证事件做出反应,您只需要 name:

<form name="form1">
    <select ng-model="foo" name="fooSelect" required>...</select>
    <span ng-show="form1.fooSelect.$dirty && form1.fooSelect.$invalid">
       You must make a selection
    </span>
</form>

至于ng-change,我绝对不同意其他关于把它变成$watch的建议。 ng-change 的用途与 $watch 不同 - 它对用户触发的更改 select 模型的事件作出反应。另一方面,$watch 会触发来自任何来源的更改。不仅如此,它还在 每个 摘要周期进行评估。因此,它在这里更昂贵且完全没有必要,不应该只是为了漂亮 HTML.

如果您正在做一些事情来响应用户更改选择,那么您应该将其保留为 ng-change