How to get the rendered content from the `link` function of a directive?

限于喜欢 提交于 2019-12-08 05:42:09

问题


Html code:

<div class="test">{{name}}</div>

Angular code:

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

app.directive('test', function(){
  return {
    restrict: 'C',
    link: function(scope, elm, attrs){
      var content = elm.html();
      alert(content);
    }
  }
});

It will alert a string {{name}}. How to alert the rendered string World?

Live demo: http://plnkr.co/edit/Mov0AlkdE9B8yKiBjpnp?p=preview


回答1:


You need to use $interpolate service to do this

app.directive('test', function($interpolate){
  return {
    restrict: 'C',
    link: function(scope, elm, attrs){
      var content = elm.html();
      alert($interpolate(content)(scope))
    }
  }
});

Demo: Fiddle



来源:https://stackoverflow.com/questions/15673134/how-to-get-the-rendered-content-from-the-link-function-of-a-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!