Alex Edwards
Alex Edwards

Reputation: 1673

Dynamic variables angular ng-repeat

I would like to be able to display some overlay when you focus on an img element. The problem is that the elements are populated from the attributes of an angularjs ng-repeat I would like only a specific img to enable a specific text.

The below example does not work, the ng-class variable resolves correctly though.

<div class="myClass" ng-repeat="i in items">
 <span class="class-img-wrapper">
  <img ng-src="{{i.img}}"  class="class-img-view" ng-init="{{i.name}}_focused = false" ng-focus="{{i.name}}_focused = true" ng-blur="{{i.name}}_focused = false"/>
  <span ng-class="{classOverlayShow: {{i.name}}_focused}" class="class-img-overlay">
    {{i.name}}
  </span>
 </span>
</div>

Upvotes: 0

Views: 1644

Answers (1)

musically_ut
musically_ut

Reputation: 34288

That does not look like valid syntax to me:

<span ng-class="{classOverlayShow: {{i.name}}_focused}" class="class-img-overlay">

It should read something along the lines of:

 <span ng-class="{classOverlayShow: i.name + '_focused' }" class="class-img-overlay">

Why not add the focussed field to your models in items?

Instead of ng-init="{{i.name}}_focused = false" and then using ng-focus="{{i.name}}_focused = true" ng-blur="{{i.name}}_focused = false" to create dynamic variables on the fly (which I suspect doesn't work because it isn't valid angular syntax), do this instead:

Controller

$scope.items.forEach(function (i) {
    i.focussed = false;
});

$scope.setOverlay = function (item) {
    item.focussed = true;
};

$scope.removeOverlay = function (item) {
    item.focussed = false;
};

Template

<div class="myClass" ng-repeat="i in items">
 <span class="class-img-wrapper">
  <img ng-src="{{i.img}}"  class="class-img-view" ng-focus="setOverlay(i)" ng-blur="removeOverlay(i)"/>
  <span ng-class="{classOverlayShow: i.focussed }" class="class-img-overlay">
    {{i.name}}
  </span>
 </span>
</div>

However, angular documentation suggests that the ngFocus directive works only for input, textarea, select, window and a tags. So for focus events, you may have to create your own directive and bind to onfocus events yourself, or switch to simpler and more ubiquitous ng-click.

Upvotes: 1

Related Questions