angularjs指令-如何添加插值属性



据我所知,如果在模板中指定了插值字符串,则它会正确扩展/解析,但如果稍后添加,则不会。为了演示,我有以下代码:

describe.only('directive tests - ', function() {
  it('add dynamic interpolated attribute value', function() {
    module(function($compileProvider) {
      $compileProvider.directive('hello', function() {
        return {
          restrict: 'A',
          replace: true,
          template: '<a foo="{{1+1}}"></a>',
          compile: function link(tElement, tAttrs) {
            tElement.attr('bar', '{{2+2}}'); // add an interpolated attr.
          }
        };
      });
    });
    inject(function($compile, $rootScope) {
      var element = angular.element('<div hello/>');
      $compile(element)($rootScope);
      $rootScope.$apply();
      console.log(' * ', element.prop('outerHTML'));
    });
  });
});

和控制台日志打印:

<a foo="2" hello="" bar="{{2+2}}" class="ng-scope"></a>'

和NOT:

<a foo="2" hello="" bar="4" class="ng-scope"></a>'

正如我想的那样。什么东西?

tElement.attr('bar', $interpolate('{{2+2}}')());

没错,在compile中执行此操作已经太晚了,更具体地说,对必须编译的指令元素本身进行更改(需要重新编译它才能使更改生效(。

但是下面的

      // replace: true,
      template: '<a foo="{{1+1}}">aa</a>',
      compile: function link(tElement, tAttrs) {
        tElement.find('a').attr('bar', '{{2+2}}');
      }

将按预期工作。

属性观察和插值也可以在link(或controller(:中完成

      link: function (scope, element, attrs) {
        attrs.$observe('bar', function (interpolatedBar) {
          scope.bar = interpolatedBar;
        });
      }

它将在bar属性上设置一个观察程序(而$interpolate(...)()是一次性赋值,不插入范围中的任何值(。

最新更新