在angularJs中从控制器中绑定ngModel,或者从ngModel中调用函数

binding ngModel from controller in angularJs or calling function from ngModel

本文关键字:ngModel 函数 或者 调用 绑定 angularJs 控制器      更新时间:2023-09-26

我正在尝试绑定一个未知的数组索引基于angularjs的一些属性。

    <select id="iditemtype" ng-model="method(entity, e)"
        ng-options="e as e.configValue for e in allConfig() | filter:{typeName:'ItemType'}">
    </select>
//javascript method inside controller
    function method()
    {
        var index = -1;
        for(var i=0;i<entity.attributes.length;i++){
            if(entity.attributes[i].type=='ItemType'){
                index = i;
                break;
            }
        }
        if(index==-1){
            entity.attributes.push(0, e);
        }
        else
            entity.attributes[index] = e;
    }
上面的示例代码是我的实际意图。我想从一个选择列表中绑定特定的属性。

我使用angularjs 1.3

这里你不能将函数传递给ng-model,因为Angular必须能够在用户改变输入值时设置该值。在这里你可以使用$watch来实现你的目标,你也可以使用ng-change指令的角度与select在这里。