AngularJS指令 - 获取元素绑定的文本内容

5

如何基于AngularJS指令restrict: 'A'获取绑定的值?

<span directiverestrict> {{binding}} </span>

我尝试使用 elem[0].innerText,但它返回的是准确的绑定 '{{binding}}' 而不是绑定的值。

.directive('directiverestrict',function() {
    return {
        restrict:'A',
        link: function(scope, elem, attr) {
            // I want to get the value of the binding enclosed in the elements directive without ngModels
            console.log(elem[0].textContent) //----> returns '{{binding}}'
        }
    };
});
4个回答

6
您可以使用$interpolate服务,例如:
.directive('logContent', function($log, $interpolate) {
  return {
    restrict: 'A',
    link: function postLink(scope, element) {
      $log.debug($interpolate(element.text())(scope));
    }
  };
});

Plunker


2
 <span directiverestrict bind-value="binding"> {{binding}} </span>

脚本

directive("directiverestrict", function () {
   return {
           restrict : "A",
           scope : {
                      value : '=bindValue'
                   },
           link : function (scope,ele,attr) {
                alert(scope.value); 
              }
      }
});

1
我不想添加任何作用域属性,有其他方法可以实现吗? - Michael Rosales
请检查@Phil Edit - Arepalli Praveenkumar

2

在链接阶段中,内部绑定不会被计算,最简单的方法是使用$timeout服务将内部内容的评估延迟到下一个digest周期中,例如:

$timeout(function() {
   console.log(elem[0].textContent);
},0);

1
FYI,0 是默认的超时时间间隔。 - Phil

0
尝试使用ng-transclude。确保在指令上设置transclude: true。我曾经认为这只是需要呈现页面上的文本。我错了。这也是我能够将值传递到我的链接函数中所需的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接