Evandro
Evandro

Reputation: 167

How to access item outside ng repeat in angularjs?

I am trying to show a data from a item that comes from ng-repeat (the number of items that results in ng-repeat is always one, because I search by code).

<script>
        var pdvApp = angular.module('pdvApp', []);

        pdvApp.controller('pdvController', function pdvController($scope) {
            $scope.itens = [
                {code: 1, name: 'Skittles', quantity: 5, price: 2.35},
                {code: 2, name: 'M&Ms', quantity: 55, price: 1.29},
                {code: 3, name: 'Gummy Bears', quantity: 5, price: 22.59},
                {code: 4, name: 'Snickers', quantity: 500, price: 0.89},
                {code: 10, name: 'KitKat', quantity: 500, price: 0.89},
            ];
});
</script>

....(inside HTML)

<input type="number" class="form-control input-lg" id="search" autofocus="" value="" ng-model="search.code"/>
<div class="col-md-8 form-group">
    <div  ng-repeat="item in filtered =(items| filter:search:true)">
        <span ng-show="filtered.length===1"><input type="text" class="form-control input-lg" id="desc" autofocus="" value="{{item.name}}"/></span>
     </div>
     <span ng-hide="filtered.length===1"><input type="text" class="form-control input-lg" id="desc" autofocus="" value="{{item.name}}"/></span>
 </div>

I'd like this to work (after the ng-repeat block, without a new ng-repeat):

Name: 
    <div class="form-group">
        <input type="text" id="name" ng-model="name" class="form-control input-lg" value="{{item.name}}" readonly=""/>
    </div>

Upvotes: 1

Views: 2183

Answers (3)

nioKi
nioKi

Reputation: 1289

I assume that "the number of items that results in ng-repeat is always one, because I search by code".

With that assumption, the item you want to fetch is the first of the filtered array.

Thus, you simply have to modify your HTML to retrieve filtered[0]

Name: 
<div class="form-group">
    <input type="text" id="name" ng-model="name" class="form-control input-lg" value="{{filtered[0].name}}" readonly=""/>
</div>

Here is a small demo: JSFiddle link.

Upvotes: 1

Sergey Romanov
Sergey Romanov

Reputation: 3080

There are few ways but you have to know index of the element

  1. In your JS file add $scope.item = $scope.items[0]; And then in HTML {{item.name}}.

  2. You can try in your HTML {{items[0].name}}

Upvotes: 1

TheSharpieOne
TheSharpieOne

Reputation: 25736

I believe you are looking for Special repeat start and end points which allow you to have sibling elements in the same repeat (rather than a root element.)

Upvotes: 2

Related Questions