如何从指令的`link`函数中获取呈现的内容?

时间:2013-03-28 02:20:13

标签: angularjs angularjs-directive

Html代码:

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

角度代码:

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);
    }
  }
});

它会提醒字符串{{name}}。如何提醒呈现的字符串World

现场演示:http://plnkr.co/edit/Mov0AlkdE9B8yKiBjpnp?p=preview

1 个答案:

答案 0 :(得分:4)

您需要使用$interpolate服务才能执行此操作

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

演示:Fiddle