Nik*_*sen 6 angularjs angularjs-compile angularjs-components
我正在尝试使用动态编译Angular组件$compile,但是范围不会传递给组件范围,而是传递给$ parent范围.
这是一个绑定到myTitle-attribute并呈现它的简单组件:
app.component('myComponent', {
bindings: {
myTitle: '<'
},
template: `
<div>
<div>Doesn't work: {{ $ctrl.myTitle}}</div>
<div>Works: {{ $parent.$ctrl.myTitle}}</div>
</div>`
});
Run Code Online (Sandbox Code Playgroud)
然后在控制器(或指令等)中使用$ 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);
});
Run Code Online (Sandbox Code Playgroud)
运行时,它会产生结果:
不起作用:
作品:我的头衔
为动态创建的组件创建的范围如何作为组件的父范围传递?
关于角度为何如此行为以及可能如何避免它的任何指针都非常受欢迎.
我看,你需要在这里传递绑定 var template = '<my-component></my-component>';
var template = '<my-component my-title="$ctrl.myTitle"></my-component>';
Run Code Online (Sandbox Code Playgroud)
完整组件可能是这样的:
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));
});
Run Code Online (Sandbox Code Playgroud)