如何从指令的`link` 函数中获取渲染的内容? [英] How to get the rendered content from the `link` function of a directive?

查看:16
本文介绍了如何从指令的`link` 函数中获取渲染的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML 代码:

{{name}}

角度代码:

var app = angular.module('angularjs-starter', []);app.controller('MainCtrl', function($scope) {$scope.name = '世界';});app.directive('test', function(){返回 {限制:'C',链接:功能(范围,榆树,属性){var content = elm.html();警报(内容);}}});

它会提醒一个字符串{{name}}.如何提醒渲染的字符串World?

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

你需要使用 $插入服务来做到这一点

app.directive('test', function($interpolate){返回 {限制:'C',链接:功能(范围,榆树,属性){var content = elm.html();警报($插值(内容)(范围))}}});

演示:小提琴

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

解决方案

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

这篇关于如何从指令的`link` 函数中获取渲染的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆