simple
simple

Reputation: 2397

AngularJS access scope from outside ng-repeat

I want to show the count of items repeated in my ng-repeat but how to I access this from outside the ng-repeat?

Plunker: http://plnkr.co/edit/SYqb8h9k81SlVY3Yzhgx

HTML:

<h3>Number of locations is: {{location.length}}</h3>

<div ng-controller="locationAccordionCtrl">
  <div ng-repeat="location in locations" on-finish-render>

    {{location.siteName}}

    <ul>
        <li ng-repeat="listOfLocations in location.locationsList track by $index">
            {{listOfLocations}}
        </li>
    </ul>

  </div>
</div>

JS:

var App = angular.module('App', []);

App.controller('locationAccordionCtrl', function ($scope) {

  $scope.locations = [
    {
      "siteName":"First Location",
      "locationsList":['First Location 1', 'First Location 2', 'First Location 3']
    },
    {
      "siteName":"Second Location",
      "locationsList":['Second Location 1', 'Second Location 2', 'Second Location 3']
    },
    {
      "siteName":"Third Location",
      "locationsList":['Third Location 1', 'Third Location 2', 'Third Location 3']
    }
  ];

});

Upvotes: 0

Views: 938

Answers (4)

Dmitri Algazin
Dmitri Algazin

Reputation: 3456

<div ng-controller="locationAccordionCtrl">

<h3>Number of locations is: {{locations.length}}</h3>

<div ng-repeat="location in locations" on-finish-render>

{{location.siteName}} ({{location.locationsList.length}})

<ul>
    <li ng-repeat="listOfLocations in location.locationsList track by $index">
        {{listOfLocations}}
    </li>
</ul>

</div>
</div>

Upvotes: 0

michelem
michelem

Reputation: 14590

Put the bind inside the controller:

<div ng-controller="locationAccordionCtrl">
  <h3>Number of locations is: {{locations.length}}</h3>
  <div ng-repeat="location in locations" on-finish-render>

    {{location.siteName}}

    <ul>
        <li ng-repeat="listOfLocations in location.locationsList track by $index">
            {{listOfLocations}}
        </li>
    </ul>

  </div>
</div>

Upvotes: 0

Fernando Pinheiro
Fernando Pinheiro

Reputation: 1816

The <h3> tag must be in the scope of the locationAccordionCtrl. So, put it inside the <div ng-controller="locationAccordionCtrl"> tag. Also, you have to say {{locations.length}} instead of {{location.length}} (missing the "s")

Upvotes: 1

Zack Tanner
Zack Tanner

Reputation: 2590

The problem is not that it is outside of ng-repeat, but rather that it is outside your controller. The following should work:

<div ng-controller="locationAccordionCtrl">
<h3>Number of locations is: {{locations.length}}</h3>
[...]

Upvotes: 0

Related Questions