angularjs - 选择选项时 ng-model 不会更新

标签 angularjs angularjs-directive angularjs-scope

我有一个带有选项列表的表单

<form class="column-form">
    <select id="classSelection" ng-change="classOptionChange()" ng-model="selectedClass" maxHeight="120">
        <option selected value="">{{classOptions}}</option>
    </select>
</form>

示例类选项位于此处

[{"id":"classR","text":" Color - Red"},{"id":"classG","text":"Color -  Green"}, {"id":"classY","text":"Color - Yellow"}]

我的指令很简单,因为我只是想打印出我选择的选项的值。但是,它始终为空。

(function() {
    appModule.directive('classDefault', [ '$translate', '$timeout', '$window', classService, function($translate, $timeout, $window, $document, classService) {
        return {
            restrict : 'E',
            scope : {
               .......
            }
        link : function(scope, element) {
            scope.classOptionChange() = function() {
                console.log(scope.selectedClass);

有什么建议吗?

更新 - 感谢以下所有建议。显然,我们正在使用这个小部件,它应该呈现选项列表,然后绑定(bind)到选择标签,但它目前已损坏。

最佳答案

您需要将数组绑定(bind)到 select 标签。一种选择是使用 NgOptions 指令。

这是一个工作示例

angular.module("app",[]).controller("ctrl", function($scope){
$scope.items = [{"id":"classR","text":" Color - Red"},{"id":"classG","text":"Color -  Green"}, {"id":"classY","text":"Color - Yellow"}];

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
<select ng-change="classOptionChange()" 
ng-model="selectedClass" 
maxHeight="120"
ng-options="item as item.text for item in items">
    </select>
    
    <h3>{{selectedClass}}</h3>
    </div>

关于angularjs - 选择选项时 ng-model 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51270572/

相关文章:

javascript - AngularJS 重定向时调用函数

javascript - AngularJS 对输入类型 'time' 的验证在 IE 中不起作用?

css - 单击时调用另一个元素上的指令

javascript - Angular 中指令和 Controller 之间的双向通信

angularjs - 在模板中使用指令 Controller 方法

jquery - 取消绑定(bind) ng-click 以 Angular 动态 dom 元素

javascript - 在 Angularjs 中多次使用 ngInclude

javascript - Angular JS 和 jqLit​​e 将节点与选择器匹配

javascript - Angular 指令 - NgModelCtrl 解析器问题

angularjs - $compile 正在为 Angular 表达式评估字符串之前加载图像