将范围变量名解析为范围函数?

时间:2013-05-30 09:01:37

标签: angularjs angularjs-scope

我有一个下拉菜单和切换下拉列表的可点击元素。当用户点击下拉菜单中的列表项时,我想将该值添加到输入框值。

我所拥有的下拉菜单会迭代一定次数,以创建一个递增数字的dropmenu列表。

<!--input-->
<input type="text" value="{{rooms}}">

<!--dropdown-->
<ul role="menu">
    <li data-ng-repeat="i in getNumber(num_of_rooms)">
        <a href="javascript:void(0);" data-ng-click="addToDropDown($index)">{{$index+1}}</a>
    </li>
</ul>



//This function simply returns an array so the dropdown menu repeats a defined number of times
$scope.getNumber = function(n) {
    return new Array(n);
};


//I want this scope function to add the value to the input by updating a scope variable
$scope.addToDropDown = function(scope_name, value){

    $scope.scope_name = value;
};

-----------

//This works but I'm defining a scope name which I would like to add dynamically as I have multiple dropdown menus
$scope.addToDropDown = function(value){

    var val = value+1;
    $scope.rooms = val;
};

有没有办法在视图本身内为范围变量赋值?

1 个答案:

答案 0 :(得分:4)

这是你想要的吗? http://plnkr.co/edit/Pew3KIoTy2fVp0tV3xv6?p=preview

给点击处理程序提供一个变量名字符串:

<a href="" ng-click="addToDropDown('rooms', $index)">
  {{ $index + 1 }}
</a>

只需在处理程序中引用给定名称的属性:

$scope.addToDropDown = function(scope_name, value) {
  $scope[ scope_name ] = value;
};