简体   繁体   English

强制AngularJS指令在摘要周期外链接

[英]Forcing AngularJS directive to link outside digest cycle

This refers to an Angular 1 application. 这是指Angular 1应用程序。

If the DOM is modified outside the context of my angular application, I know I can use angular.element(document.body).scope().$apply() to force the whole app to re-render, including the newly injected content. 如果在我的角度应用程序上下文之外修改了DOM,我知道我可以使用angular.element(document.body).scope().$apply()强制重新渲染整个应用程序,包括新注入的内容。

However my directives never seem to link. 但是,我的指令似乎从未链接过。

So in the example below, the markup <message></message> should render Hello World , but when it is injected manually, then digest applied, the link method never appears to run. 因此,在下面的示例中,标记<message></message>应该呈现Hello World ,但是当手动注入它然后应用摘要时, link方法似乎永远不会运行。

https://jsbin.com/wecevogubu/edit?html,js,console,output https://jsbin.com/wecevogubu/edit?html,js,console,output

javascript JavaScript的

var app = angular.module('app', [])

app.directive('message', function() {
  return {
    template: 'Hello, World!',
    link: function() {
      console.log('message link')
    }
  }
})

document.getElementById('button').addEventListener('click', function() {
  document.getElementById('content').innerHTML = '<message>default content</message>'
  var scope = window.angular.element(document.body).scope()
  scope.$apply()
})

html HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</head>
<body ng-app="app">
  inside app:
  <message></message>

  outside app:
  <button id="button">Print another message</button>
  <div id="content"></div>
</body>
</html>

According to the docs, you can do this with angular.injector 根据文档,您可以使用angular.injector进行此操作

angular.injector allows you to inject and compile some markup after the application has been bootstrapped angular.injector允许您在应用程序启动后注入并编译一些标记

So the code for your example could be: 因此,您的示例代码可能是:

document.getElementById('button').addEventListener('click', function() {
  var $directive = $('<message>default message</message>');
  $('#content').append($directive);

  angular.element(document.body).injector().invoke(function($compile) {
    var scope = angular.element($directive).scope();
    $compile($directive)(scope);
  });
})

在此处输入图片说明

Hope this is what you are looking for! 希望这是您想要的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM