afn afn - 7 months ago 18
HTML Question

Angular - Choose from list and set to button

I have this directive :

app.directive('sampleDirective' , function () {
return {
controller: function ($scope) {
$scope.numbers = [
{number : '1 '},
{number : '2 '},
{number : '3'},
{number : '4'},
];
}
}
});


I call this number in list like this:

<sample-directive>
<button type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="btn btn-dropdown dropdown-toggle">choose number<i class="icon icon-arrow-down"></i></button>
<ul class="dropdown-menu list-unstyled text-right">
<ul>
<li ng-repeat="x in numbers">
<a href = "#"> {{ x.number }} </a>
</li>
</ul>
</ul>
</sample-directive>


At this moment , list can show numbers but I want to change choose number to selected value..(for example if I choose 1 I want to set it as value of button) How to do that?

Answer

In your controller:

$scope.setSelectedNumber = function(n) {
    $scope.selectedNumber = n;
}

In your link:

<a href="" ng-click="setSelectedNumber(x.number)"> {{ x.number }} </a>

In your button:

{{ selectedNumber ? selectedNumber : 'choose number' }}

or even simpler:

{{ selectedNumber || 'choose number' }}
Comments