简体   繁体   中英

AngularJS - Dynamic scope fields

It is possible to use a dynamic parameter and set his scope value?

$scope.testFunc= function(fieldName){

  $scope.fieldName = 'Test';
}

JSFiddle

var app = angular.module('myApp', []);

function myCtrl($scope, $parse) {
    $scope.coolform = {};
    $scope.testFunc = function(fieldName){
        var model = $parse(fieldName);
        model.assign($scope, 'test2');
    }
}

or you could use your own directive instead of ng-click, and use = as described here how to set an interpolated value in angular directive?

You need to set like this:

$scope.testFunc= function(fieldName){

    $scope[fieldName] = 'Test';
}

If you want nesting like this:

fieldName.secondLevel

you could use:

$scope[fieldName][secondLevel]

Or you use the regex parser used by angular. (I don't know how to use this one...)

EDIT:

The regular expression copied from the sourcecode:

                       //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/

and the usage:

        var match;

    if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
      throw ngOptionsMinErr('iexp',
        "Expected expression in form of " +
        "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
        " but got '{0}'. Element: {1}",
        optionsExp, startingTag(selectElement));
    }

    var displayFn = $parse(match[2] || match[1]),
        valueName = match[4] || match[6],
        keyName = match[5],
        groupByFn = $parse(match[3] || ''),
        valueFn = $parse(match[2] ? match[1] : valueName),
        valuesFn = $parse(match[7]),
        track = match[8],
        trackFn = track ? $parse(match[8]) : null,
        // This is an array of array of existing option groups in DOM.
        // We try to reuse these if possible
        // - optionGroupsCache[0] is the options with no option group
        // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
        optionGroupsCache = [[{element: selectElement, label:''}]];

As you see, they use $parse to get the values for the selected expression like fieldName.secondLevel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM