指定指令的元素上不相关属性中的未处理表达式

时间:2012-11-10 04:08:01

标签: javascript angularjs

我有一个带有span元素的HTML,它指定了一个指令:

<div ng-controller="MyCtrl">
  <span id="theSpan" my-directive="{{data.one}}" title="{{data.two}}">
</div>

该指令将一些HTML附加到元素:

var myApp = angular.module('myApp', []);

myApp.directive('myDirective', function() {
  return {
    template: "<div>{{text}}</div>",
    scope: {
      text: "@myDirective"
    }
  };
});

function MyCtrl($scope) {
  $scope.data = {
    one: 'One!!',
    two: 'Two!!'
  };
}

此代码产生以下DOM结构:

<div ng-controller="MyCtrl" class="ng-scope">
  <span id="theSpan" my-directive="One!!" title="" class="ng-isolate-scope ng-scope">
    <div class="ng-binding">One!!</div>
  </span>
</div>

问题是titlespan属性中缺少的数据。我可以通过向范围添加title: '@'来使其正常工作,如下所示:

myApp.directive('myDirective', function() {
  return {
    template: "<div>{{text}}</div>",
    scope: {
      text: "@myDirective",
      title: '@' // <-- added
    }
  };
});

导致这个DOM:

<div ng-controller="MyCtrl" class="ng-scope">
  <span id="theSpan" my-directive="One!!" title="Two!!" class="ng-isolate-scope ng-scope">
    <div class="ng-binding">One!!</div>
  </span>
</div>

如何对我的指令进行编码,以便保留元素上的属性,而不必在指令的范围内指定它们? (也许更好的问题是:为什么不评估title属性?)

以下a jsFiddle证明了这个问题。

1 个答案:

答案 0 :(得分:1)

问题是通过做

scope: {
  text: "@myDirective"
}

您正在为span元素创建一个独立的范围。因此,当{{data.two}}被评估时,范围中没有data属性。 '@myDirective'允许评估该属性并将其插入隔离范围。这就是'@'为标题工作的原因。一种解决方案可能是不对指令使用隔离范围,然后使用$observe在指令范围内设置text。见http://jsfiddle.net/sEMeA/9/

相关问题