在组件上使用$ compile时,为什么作用域通过$ parent传递? [英] When using $compile on component, why is the scope passed through $parent?

查看:52
本文介绍了在组件上使用$ compile时,为什么作用域通过$ parent传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 $ compile 动态编译Angular组件,但范围未传递给组件范围,而是传递给了$ parent范围.

I'm trying to dynamically compile an Angular component using $compile, but the scope isn't passed to the components scope, but to the $parent scope instead.

这是绑定到 myTitle 属性并显示的简单组件:

Here is a simple component that binds to a myTitle-attribute and presents it:

app.component('myComponent', {
  bindings: {
    myTitle: '<'
  },
  template: `
    <div>
      <div>Doesn't work: {{ $ctrl.myTitle}}</div>
      <div>Works: {{ $parent.$ctrl.myTitle}}</div>
    </div>`
});

然后在控制器(或指令等)中,我使用$ compile对其进行编译:

Then in the controller (or directive, etc.) I compile it using $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);
  
});

运行此命令时,将产生结果:

When running this, it yield the result:

不起作用:

作品:我的标题

这是一个在行动中展示它的朋克

我为动态创建的组件创建的作用域如何作为组件的父作用域传递?

How come the scope I create for the dynamically created component, is passed as a parent scope of the component?

关于角度为什么会如此行为以及如何避免这种行为的任何指针都是很受欢迎的.

Any pointer on why angular behaves like this and perhaps how to avoid it is much welcome.

推荐答案

如我所见,您需要在此处传递绑定 var template ='< my-component></my-component>';

As I see, you need to pass binding here var template = '<my-component></my-component>';

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

完整的组件可能是这样的:

Full component may be like this:

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)); 
});

这篇关于在组件上使用$ compile时,为什么作用域通过$ parent传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆