编译从JSON文件AngularJS注入指令 [英] Compile directive that is injected from a JSON file AngularJS

查看:227
本文介绍了编译从JSON文件AngularJS注入指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人能帮助我这个挑战。

我使用从服务器请求JSON数据 $ http.get();

来自服务器的数据返回一个对象。在对象的一个​​值包含HTML标记。此标记是用注入到页面< D​​IV NG绑定HTML的不安全=内容/>

在标记中,有一个名为自定义指令<轮询/>

使用标准AngularJS指令结构,它不拿起指令,并将其链接。

我怎么能编译这个HTML一旦从服务器中检索并调用指令链接功能?

谢谢!


解决方案

$编译服务是你想要的。

$编译服务可以注入控制器或指令,并调用一个模板。它会返回一个链接功能,可以打电话,传递你要链接的范围。

下面是一个例子:

\r
\r

angular.module('应用',[]);\r
\r
angular.module(应用)。控制器('MainCtrl',函数($编译,$ rootScope){\r
  VAR模板='<特殊指令道具=myProp> < /特殊指令>';\r
  VAR范围= $ rootScope $新的()。\r
  VAR顶部=的document.getElementById('顶');\r
  scope.myProp ='问好你母亲为我';\r
  top.innerHTML =模板;\r
  \r
  $编译(上)(范围);\r
})\r
\r
angular.module(应用)。指令(specialDirective',函数(){\r
返回{\r
      适用范围:{道具:'='},\r
      限制:'E',\r
      链接:功能(范围,ELE){\r
        VAR HTML ='你好从特殊指令< BR />< BR />' + scope.prop;\r
        ele.html(HTML);\r
      }\r
    }\r
})

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r
&LT; D​​IV NG-应用=应用程序NG控制器=MainCtrl&GT;\r
  &LT; D​​IV ID =顶&GT;&LT; / DIV&GT;\r
&LT; / DIV&GT;

\r

\r
\r

Hoping someone can help me with this challenge.

I request JSON data from the server using $http.get();

The data from the server returns an object. One value in the object contains HTML markup. This markup is injected to the page using <div ng-bind-html-unsafe="content" />

Within the markup, there is a custom directive named <poll />

Using the standard AngularJS directive structure, it does not pick up the directive and link it.

How can I compile this HTML once retrieved from the server and call the link function on the directive?

Thanks!

解决方案

The $compile service is what you want.

The $compile service can be injected into a controller or directive and invoked on a template. It will return a linking function which you can call, passing in the scope that you want to link.

Here's an example:

angular.module('app', []);

angular.module('app').controller('MainCtrl', function ($compile, $rootScope) {
  var template = '<special-directive prop="myProp"> </special-directive>';
  var scope = $rootScope.$new();
  var top = document.getElementById('top');
  scope.myProp = 'Say hello to your mother for me';
  top.innerHTML = template;
  
  $compile(top)(scope);
})

angular.module('app').directive('specialDirective', function () {
	return {
      scope:{ prop: '=' },
      restrict: 'E',
      link: function (scope, ele) {
        var html = 'Hello from the special directive<br/><br/>' + scope.prop;
        ele.html(html);
      }
    }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
  <div id="top"></div>
</div>

这篇关于编译从JSON文件AngularJS注入指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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