gpt4 book ai didi

angularjs - 在组件上使用 $compile 时,为什么范围是通过 $parent 传递的?

转载 作者:行者123 更新时间:2023-12-04 15:07:55 25 4
gpt4 key购买 nike

我正在尝试使用 $compile 动态编译 Angular 组件,但范围不会传递给组件范围,而是传递给 $parent 范围。
这是一个绑定(bind)到 myTitle 的简单组件。 - 属性并呈现它:

app.component('myComponent', {
bindings: {
myTitle: '<'
},
template: `
<div>
<div>Doesn't work: {{ $ctrl.myTitle}}</div>
<div>Works: {{ $parent.$ctrl.myTitle}}</div>
</div>`
});
然后在 Controller (或指令等)中,我使用 $compile 编译它:
app.controller('MainCtrl', function($scope, $element, $compile) {
var template = '<my-component></my-component>';

var bindings = {
myTitle: 'My Title'
}
var scope = angular.extend($scope.$new(true), {
$ctrl: bindings
});
var newElement = $compile(template)(scope);
$element.append(newElement);

});
运行它时,它会产生结果:

Doesn't work:

Works: My Title


Here's a plunker showing it in action
问题
我为动态创建的组件创建的范围如何作为组件的父范围传递?
任何关于 Angular 为何如此行为以及如何避免它的指针都非常受欢迎。

最佳答案

如我所见,您需要在此处通过绑定(bind) var template = '<my-component></my-component>';

var template = '<my-component my-title="$ctrl.myTitle"></my-component>';

完整的组件可能是这样的:
app.controller('MainCtrl', function($scope, $element, $compile) { 
var template = '<my-component my-title="$ctrl.myTitle"></my-component>';
$scope.$ctrl = {myTitle: 'My Title'};
$element.append($compile(template)($scope));
});

关于angularjs - 在组件上使用 $compile 时,为什么范围是通过 $parent 传递的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44262450/

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