gpt4 book ai didi

javascript - AngularJS DOM 注入(inject)

转载 作者:行者123 更新时间:2023-11-30 16:42:48 24 4
gpt4 key购买 nike

如果我提前向 AngularJS 注册了一个面向元素的指令,那么我是否可以简单地直接向 DOM 中注入(inject)(例如通过 document.appendChild )一个与指令元素匹配的节点(例如 <my-directive-name my-attribute='foo'></my-directive-name> ),AngularJS 将渲染说指令代替它(可能需要手动摘要触发器)?

我的指令模板.html

  <div>
hello world
</div>

我的指令名称.js

function MyDirectiveName() {
return {
scope: {
'myAttribute': '&',
},
template: template,
replace: true,
controller: controller,
restrict: 'E',
// ...
};
}

Angular 配置:

//...
angular.directive('my-directive-name', require('my-directive-name'))
//...

启动 DOM:

<body></body>

然后我动态附加一个子节点:

<body>
<my-directive-name my-attribute='foo'>
</my-directive-name>
</body>

然后我做一些事情让 Angular 意识到有些东西已经改变了(这是什么?):

结束 DOM:

<body>
<div>
hello world
</div>
</body>

最佳答案

您需要确保 $compile在将元素附加到 DOM 之前首先添加元素。这是一个简单的示例,展示了如何在 Angular 代码之外(通过 setTimeout)使用 $compile 函数来添加到 DOM。

(function(angular) {

angular.module('myApp', [])
.directive('myDirectiveName', MyDirectiveName);

function MyDirectiveName() {
return {
restrict: 'E',
template: '<div>Custom Directive with {{myAttr}} as my-attribute</div>',
scope: {
myAttr: '@myAttribute'
}
};
}

// run this later.
setTimeout(function() {

var appDiv = angular.element(document.getElementById('app'));
// Get the injector to compile
var $injector = appDiv.injector();
var $compile = $injector.get('$compile');
// compile new elems
var barLink = $compile(angular.element('<my-directive-name my-attribute="bar"></my-directive-name>'));
var bazLink = $compile(angular.element('<my-directive-name my-attribute="baz"></my-directive-name>'));

// append both elements by linking against scope
appDiv.append(barLink(appDiv.scope()));
appDiv.append(bazLink(appDiv.scope()));
}, 3000);
}(angular));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" id="app">
<my-directive-name my-attribute="foo"></my-directive-name>
</div>

关于javascript - AngularJS DOM 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31683220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com