计算指令属性中的表达式

时间:2015-04-16 14:16:49

标签: angularjs directive

使用AngularJS,我正在寻找一种用"变量"来评估表达式的方法。在指令的属性中。

例如,在下面的 textbox 指令中,我希望属性 top 评估结果为&#34; 10 + index * 25&#34; < / p>

<template resource="api/data.json">
    <!-- usage of textbox component -->
    <textbox name="lblNames" text="name" top="10+index*25" left="11">
</template>
这里的

索引应该是textBox模板中ng-repeat的迭代值(见下文)。 (另一个例子: lblNames 将引用并返回组件本身。)

<!-- template for textBox component -->
<div ng-repeat="row in rows" 
     style="left : {{components.left}}px; 
            top  : {{components.top }}px;">

  {{row[components.text]}}

</div>

到目前为止,我找到的最好的方法是使用$ parse,它允许我评估简单的表达式,例如&#34; 1 + 1&#34;如下面的代码所示。但是我如何使用&#34;动态属性评估表达式&#34;喜欢:10 +指数* 25?

angular.module("uvis").directive("uvisTextbox", function($parse, $compile) {
    return { 
    scope : {
      test : '@'
    },
        restrict : 'E',
        require : '^uvisBundle',
        link : function( scope, element, attributes, uvisBundleCtrl) {
      console.log( element );
      uvisBundleCtrl.addComponent({
        text : attributes.text,
                top : $parse( attributes.top )(scope),
                left : $parse( attributes.left )(scope),
        debug : "empty"
          });
            console.log("linked uvisTextbox");
        },
    controller : function($scope) {
      $scope.test = 'test';
    }
    };
})

为了更容易理解程序是如何工作的,我在这里制作了JSFiddle: https://jsfiddle.net/wxcx7ap3/7/

更新(解决方案)

我设法通过在textBox模板中进行评估来使其工作:

<!-- template for textBox component -->
<div ng-repeat="row in rows" 
     style="left : {{$eval( components.left) }}px; 
            top  : {{$eval( components.top) }}px;">

  {{row[components.text]}}

</div>

当然我更新了

top : $parse( attributes.top )(scope)

top : attributes.top
指令中的

完整示例:http://jsfiddle.net/wxcx7ap3/9/

2 个答案:

答案 0 :(得分:2)

使用插值。 Angular使用$interpolate服务评估大括号内的表达式,尝试使用当前scope的上下文“解析”表达式中的所有变量。

所以在你的情况下:

<textbox name="lblNames" text="name" top="{{ 10+index*25 }}" left="11">

Angular将搜索当前范围的index值并计算该值。此外,当Angular看到花括号时,它会在表达式上放置watch并在每次值更改时更新它。

答案 1 :(得分:0)

我在角度模板中评估这样表达

 <td>{{ ( data.totalDurationOutgoing-0) + (data.totalDurationIncoming-0 ) }}</td>
相关问题