AngularJs 将模型值+模型名称传递给控制器​​中的函数

AngularJs pass model value + model name to function in controller

$scope.populateMap=[{name: "ABC", code: "123"}, {name: "XYZ", code: "345"}]

//要发送模型名+模型值当前发送ngObject.MainObj.specificFormatObj

HTML

<select ng-model="ngObject.MainObj.specificFormatObj" ng-change="ngObject.MainObj.specificFormatObj">
    <option></option>
    <option ng-repeat="i in populateMap" value="{{i}}">{{i.name}}</option>

JS

// CONTROLLER CODE JSON parse object to get name and code GOT parsedObj
$scope.genericSetLookups=function (Obj) {  // want to do something like get the ngmodel string + the value, currently only value comes in
    Obj.code=parsedObj.code;
    Obj.name=parsedObj.name
};

更多说明:ngObject.MainObj.specificFormatObj

我不是很理解你的问题,评论也没有让我更清楚。我试图做的是给你一个例子,说明我将如何处理 select 框和模型。

我会使用 ng-options 遍历选项,并通过在模板中放置 {{selected.name}} 来显示 selected 选项。当然,如果您无论如何都想格式化 selected 值或对更改做出反应,您可以使用 ng-change.

希望对您有所帮助。

Here is my JSFiddle

我不确定我是否理解你的问题。如果你想在你的模型中保存值代码+名称,也许这段代码可以帮助你:

 <select ng-model="ngObject.MainObj.specificFormatObj" ng-options="(ppm.code + '-' + ppm.name) as ppm.name for ppm in populateMap">
 </select>

jsfiddle

由于您需要将型号名称作为参数传递,因此将其作为字符串传递,如下所示 html :

ng-change="genericSetLookups('ngObject.SomeObject.abc',ngObject.SomeObject.abc)"

并且在控制器中作为型号名称包含“.”。我们不能直接使用名称作为键。我们需要解析模型名称。经过一番搜索后,我做了一些东西。希望它有效。

控制器代码:

    $scope.genericSetLookups(modelName, value){
        Object.setValueByString($scope, modelName, value);
    }

    Object.setValueByString = function(o, s, val) {
    s = s.replace(/\[(\w+)\]/g, '.'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            if(i != n-1){
                o = o[k];
            }
            else{
                o[k] = val;
            }
        } else {
            return;
        }
    }
    return o;
  }

答谢还得转给@Alnitak here