动态变量角度ng-repeat

时间:2013-11-20 20:56:14

标签: angularjs

我希望能够在关注img元素时显示一些叠加层。问题是元素是从angularjs ng-repeat的属性填充的。我只想要一个特定的img来启用特定的文本。

以下示例does not workng-class变量可以正确解析。

<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>

1 个答案:

答案 0 :(得分:1)

这对我来说看起来不像是有效的语法:

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

应该阅读以下内容:

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

为什么不在focussed中将items字段添加到模型中?

而不是ng-init="{{i.name}}_focused = false",然后使用ng-focus="{{i.name}}_focused = true" ng-blur="{{i.name}}_focused = false"动态创建动态变量(我怀疑它不起作用,因为它不是有效的角度语法),请改为:

<强>控制器

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

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

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

<强>模板

<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>

但是,angular documentation表明ngFocus指令仅适用于inputtextareaselectwindow和{{1} }标签。因此,对于焦点事件,您可能必须自己创建自己的指令并绑定到a事件,或者切换到更简单且更普遍的onfocus