编译从JSON文件AngularJS注入指令指令、文件、JSON、AngularJS

2023-09-13 03:36:37 作者:该怎么生活

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

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

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

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

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

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

谢谢!

解决方案

的的 $编译服务是你想要的。

Javascript教程 JS教程 技术文章

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

下面是一个例子:\r\r

angular.module('应用',[]);\r\rangular.module(应用)。控制器('MainCtrl',函数($编译,$ rootScope){\r  VAR模板='<特殊指令道具=myProp> < /特殊指令>';\r  VAR范围= $ rootScope $新的()。\r  VAR顶部=的document.getElementById('顶');\r  scope.myProp ='问好你母亲为我';\r  top.innerHTML =模板;\r  \r  $编译(上)(范围);\r})\r\rangular.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>