AngularJS - 动态范围字段

时间:2014-07-14 11:05:48

标签: javascript angularjs

可以使用动态参数并设置其范围值吗?

$scope.testFunc= function(fieldName){

  $scope.fieldName = 'Test';
}

3 个答案:

答案 0 :(得分:2)

JSFiddle

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

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

或者您可以使用自己的指令而不是ng-click,并使用此处所述的= {{1}}

答案 1 :(得分:1)

您需要像这样设置:

$scope.testFunc= function(fieldName){

    $scope[fieldName] = 'Test';
}

答案 2 :(得分:1)

如果你想要这样嵌套:

fieldName.secondLevel

你可以使用:

$scope[fieldName][secondLevel]

或者您使用angular使用的正则表达式解析器。 (我不知道如何使用这个......)

编辑:

从源代码复制的正则表达式:

                       //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]+?))?$/

和用法:

        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:''}]];

如您所见,他们使用$ parse来获取所选表达式的值,如fieldName.secondLevel