kfm
kfm

Reputation: 143

$index in controller Angular

I would like to get my value from select ng-model="NumProdutos[$index]" if I click in the button.

The possibles values in this select is '1, 2, 3' and this select is inside a div with a ng-repeat

Here its my html code:

<select class="form-control"
        style="max-width:55%;"
        ng-model="NumProdutos[$index]"
        ng-options="obj.NumProdutos as obj.NumProdutos for obj in NumeroProdutos"
        ng-change="functionnumprodutos(NumProdutos[$index], {{x[0].NumPostoAgendamento}})"></select>

<input type="submit" value="teste" ng-click="teste($index)" class="btn btn-primary" />

Controller

$scope.teste = function (a) {
    console.log('a: ', a);

    console.log('N NumProdutos: ', $scope.NumProdutos[a]);
    console.log('N NumProdutos: ', $scope.NumProdutos);
    console.log('N NumProdutos: ', $scope.NumProdutos[$index]);
}

I tried console.log, but I didn't know how to get this values of ng-model="NumProdutos[$index]"

Upvotes: 0

Views: 1295

Answers (2)

Alexis
Alexis

Reputation: 842

The problem is $index is defined only for ng-repeat, not ng-options. So please proceed with following method, you will get the index in ng-change itself. Thank you

function LoginController($scope) {

    $scope.NumeroProdutos = [{"NumProdutos":1},{"NumProdutos":2},{"NumProdutos":3}];
    $scope.itemIndex = null;
$scope.getIndex = function (a) {
   console.log(a);
   console.log('N NumProdutos: ', $scope.NumeroProdutos[a]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="LoginController">

<select class="form-control" ng-init="indexvalue"
    style="max-width:55%;"
    ng-model="NumProdutos" 
    ng-options="obj.NumProdutos for obj in NumeroProdutos"
    ng-change="getIndex(NumeroProdutos.indexOf(NumProdutos));">
</select>

</div>

Upvotes: 0

Sangwin Gawande
Sangwin Gawande

Reputation: 8156

Try This :

HTML :

<select class="form-control"
    style="max-width:55%;"
    ng-model="NumProdutos[$index]"
    ng-options="obj.NumProdutos as obj.NumProdutos for obj in NumeroProdutos"
    ng-change="getIndex($index);functionnumprodutos(NumProdutos[$index], {{x[0].NumPostoAgendamento}})">
</select>

<input type="submit" value="teste" ng-click="teste(itemIndex)" class="btn btn-primary" />

Controller :

$scope.itemIndex = null;
$scope.getIndex = function (a) {
    $scope.itemIndex = a;
}

$scope.teste = function (a) {
    console.log('a: ', a);
    console.log('N NumProdutos: ', $scope.NumProdutos[a]);
    console.log('N NumProdutos: ', $scope.NumProdutos);
    console.log('N NumProdutos: ', $scope.NumProdutos[$index]);
}

Upvotes: 0

Related Questions