javascriptangularjsangularjs-directiveangularjs-scopeangular-controller

AngularJs pass model value + model name to function in controller


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

//Want to send model name + value of model Currently sending 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
};

More Explanation: ngObject.MainObj.specificFormatObj


Solution

  • Since you need to pass the model name as a parameter, pass it as a string like this from html :

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

    And in the controller as the model name contains "." we cannot use the name directly as the key. We need to parse the model name. I have cooked something up after searching a bit. Hope it works.

    Controller code:

        $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;
      }
    

    Credit must also go to @Alnitak for the answer here