eric
eric

Reputation: 385

Angular access to bound element

It may be an issue in the way i'm architecting my application, but i keep running into the need to be able to access the dom element via my items array:

$scope.items = [{"src": src, "url": url, "title": title, "top": 0, "left": -500 }];

Bound to html with:

<div class="block" ty-stacked-block ng-repeat="item in items" ng-style="{ 'top' : item.top+'px', 'left' : item.left+'px' }">
  <a href="{{ item.url }}" title="{{ item.title }}">
    <img ng-src="{{ item.src }}" alt="{{ item.title }}" />
  </a>
  <br />
  <p>{{ item.title }}</p>
</div>

Basically I have another piece of code that wants to run through $scope.items and make changes to the div's positioning (based on each div's height).

    scope.repositionItems = function() {
        _.each(scope.items, function(item) {
            // TODO get item's height somehow
        });
    };

Upvotes: 4

Views: 2086

Answers (2)

Apocalypse
Apocalypse

Reputation: 69

I am not sure why you have layout attributes in your items list, hopefully you don't have a good reason and this will help. If your intention is to have several element blocks stacked on top of each other each containing a result from items then you should let angular repeat the items and not position them at all yourself. Your style attributes in class='block' should create the desired spacing and layout. I have wrapped your code in a unordered list and changed the div tag to an li tag. You can always retain the div inside the li tag. If you don't want to wrap with a ul then apply float:left in class="block"

    <ul>
    <li class="block" ng-repeat="item in items">
      <a href="{{ item.url }}" title="{{ item.title }}">
       <img ng-src="{{ item.src }}" alt="{{ item.title }}" />
      </a>
      <br />
      <p>{{ item.title }}</p>
    </li>
    </ul>

.block {
    background-color:#fff;
    width:400px;
    padding:10px;
    border-radius:8px;
    margin:10px;
    position: relative;
}

Upvotes: 0

eric
eric

Reputation: 385

I added an id to the div "item-{{ $index }}", so i could fetch it by id from my loop. Doesn't feel very "angular", but it worked!

<div id="item-{{ $index }}" class="block" ty-stacked-block ng-repeat="item in items" ng-style="{ 'top' : item.top+'px', 'left' : item.left+'px' }">
  <a href="{{ item.url }}" title="{{ item.title }}">
    <img ng-src="{{ item.src }}" alt="{{ item.title }}" />
  </a>
  <br />
  <p>{{ item.title }}</p>
</div>

Upvotes: 4

Related Questions