代码之家  ›  专栏  ›  技术社区  ›  NeverGiveUp161

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

  •  1
  • NeverGiveUp161  · 技术社区  · 8 年前
    $scope.populateMap=[{name: "ABC", code: "123"}, {name: "XYZ", code: "345"}]
    

    //要发送当前发送ngObject的模型的模型名称+值。MainObj公司。特定格式对象

    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公司。特定格式对象

    • 我希望在我的模型中以一种特定的方式存储查找值,包括名称和代码。在UI上,我使用ng repeat进行填充,因此当我选择一个特定值时,我可以将I.name作为显示,将值设置为I.code。
    • 但如果我这样做,我的ngObject。MainObj公司。特定格式对象。名称将为null,值将设置为ngObject。MainObj公司。特定格式对象。通过使用ng模型进行编码,这就是我在值中使用I的原因,而不是I.code或I.value,现在在映射中我有了代码和名称对。
    • 我将其发送到一个函数并对其进行解析,然后将值设置为ngObject。MainObj公司。特定格式对象。代码=InputOfUnc。名称分别为代码。在这种情况下,在ng更改中,我传递给ngObject。MainObj公司。特定格式对象。代码,而是要将i从映射设置为ngObject。MainObj公司。specificFormatObj还将其发送给函数模型字符串,在本例中,该字符串将是“ngObject.MainObj.specificFormatObj”。
    • 因此,对于10个查找,我可以编写一个通用代码,其中可以将模型名称和模型值作为参数发送到函数并在那里进行设置,上述方法可能是硬编码值,我想以特定格式将其设置为模型。
    3 回复  |  直到 8 年前
        1
  •  1
  •   Flemin Adambukulam    8 年前

    由于需要将模型名称作为参数传递,因此可以从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, '.$1'); // 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

        2
  •  0
  •   digijap    8 年前

    我没有真正理解你的问题,评论也没有让我更清楚。我想做的是给你一个我如何处理选择框和模型的例子。

    我会用 ng-options 并通过放置 {{selected.name}} 在模板中。当然,如果您希望以任何方式格式化所选值,或者对您可以使用的更改作出反应 ng-change

    希望有帮助。

    Here is my JSFiddle

        3
  •  0
  •   Josito    8 年前

    我不确定我是否理解你的问题。如果要在模型中保存值代码+名称,可能此代码可以帮助您:

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

    jsfiddle