Malcr001
Malcr001

Reputation: 8289

Parse scope variable name to scope function?

I have a dropdown menu and the clickable element that toggles the dropdown. When the user clicks on a list item in the dropdown menu I want to add that value to the input boxes value.

The dropdown menu I have is iterated a defined number of times to create a dropmenu listing incremented numbers.

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

Is there a way to assign a new value to the scope variable inside the view itself?

Upvotes: 2

Views: 6336

Answers (1)

Tosh
Tosh

Reputation: 36030

Is this what you want? http://plnkr.co/edit/Pew3KIoTy2fVp0tV3xv6?p=preview

give a string of the variable name to the click handler:

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

just refer the property of the given name in the handler:

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

Upvotes: 4

Related Questions