错误:ngModel:不可分配的表达式

Error: ngModel: Non-Assignable Expression

本文关键字:表达式 可分配 不可分 ngModel 错误      更新时间:2023-09-26

我有动态生成下拉列表的代码。我想使用ng重复设置选定的值,为此我使用了ng模型中的函数,但我得到了

Error: [ngModel:nonassign] Expression 'item.blockName = getCurrentComboBoxValue(item.blockName.id, blockNameOptions)' is non-assignable. Element: <select class="form-control input-sm" ng-model="item.blockName = getCurrentComboBoxValue(item.blockName.id, blockNameOptions)" name="blockName" ng-options="choice.id as choice.value for choice in blockNameOptions">

HTML

<div ng-repeat="item in modulesData.blocks track by item.id">
    <select class="form-control input-sm" ng-model="item.blockName = getCurrentComboBoxValue(item.blockName.id, blockNameOptions)" name="blockName" 
        ng-options="choice.id as choice.value for choice in blockNameOptions">
    </select>
</div>

控制器

$scope.getCurrentComboBoxValue = function (id, availableData) {
    var result = _.where(availableData, { 'id': id });
    return result[0];
}

getCurrentComboBoxValue(blockNameOptions)=的左侧无效。ngModel要求左边的东西是可赋值的。

我认为您正在尝试做angular为您所做的事情。如果为angular指定一个特性的"名称"以将选定的值指定给它,则会自动绑定该值。当它发生变化时。在您的情况下,selectedValue将为choice.id。这个值可以是作用域上现有的东西,也可以将其分配给作用域。例如:

<div ng-repeat="item in modulesData.blocks track by item.id">
    <select class="form-control input-sm" ng-model="selectedItem" name="blockName" 
    ng-options="choice.id as choice.value for choice in blockNameOptions">
    </select>
    <div>I selected  {{selectedItem}}</div>
</div>

在您的Ctrl中,您可以执行

$scope.getCurrentComboBoxValue = function (id, availableData) {
    console.log($scope.selectedItem);
}

如果您默认为$scope.selectedBlock=,则它会默认为您选择。