【问题标题】:In Angular 1.5, how to compile the html of a parent component from a child component?在 Angular 1.5 中,如何从子组件编译父组件的 html?
【发布时间】:2016-08-30 16:37:08
【问题描述】:

我有两个角度分量:app-menuitemapp-menu。 app-menu 有一个作为子项的 app-menuitem 列表,但没有嵌入。

应用菜单项

angular.module('app')
    .component('appMenuitem', {
      transclude: false,
      controller: menuitemController,
      require: {
        parent: '^?app-menu'
      },
      bindings: {
        ...
        groupradio: '@',        
        isactive: '<', // bind to active (just init)
        ...
      },
      templateUrl: 'angular/components/simple/menuitem/menuitem.html'
    });

function menuitemController($rootScope, $scope, $element, $attrs) {
    var ctrl = this;

    //Default values
    ctrl.$onInit  = function () {
      if(ctrl.isactive){
        ctrl.active = true;
      }else{
        ctrl.active = false;
      }
      ctrl.selectRadioItem = function(){
          if(!ctrl.active){
             var currentMenu = this.parent.items.menu;
             var levelMenu = this.parent.items.level;
             for(var i = 0; i < currentMenu.length; i++){
                var currentMenuItem = currentMenu[i];
                if(currentMenuItem.groupradio === ctrl.groupradio){
                    if(currentMenuItem.index === ctrl.index){
                        currentMenuItem.isactive = true;
                    }else{
                        currentMenuItem.isactive = false;
                    }
                    currentMenu[i] = currentMenuItem;
                }
            }
            this.parent.items.menu = currentMenu;
            console.dir(this.parent); //<-- updates are visible but the html did not change. 
          }
          ...

正如您在这段代码末尾看到的那样,我设法从这个子组件app-menuitem 修改了父组件 app-menu,但在这种情况下,HTML 再也不会编译了。有人有想法吗?

【问题讨论】:

  • 为什么不使用数据绑定?
  • 我正在使用“绑定”属性...你是什么意思?
  • 您介意发布菜单项的 html 吗?

标签: angularjs angular compilation components parent-child


【解决方案1】:

我建议不要直接从子级更改父级的值。相反,在父控制器上公开一个方法,该方法是从具有所需更新的子调用的,并让父处理更新。 这使您既可以避免成本更高的绑定,又可以将控制器属性的控制权保留在控制器本身中(因此,您可以更轻松地在代码中找到错误源)。如果您正在测试您的代码,它也更易于测试。

小提示:出于测试目的,如果某些内容在您之后没有更新 更新模型,你总是可以尝试在 $scope.$apply() 之后 更新并查看是否存在$digest 时间问题。 请勿用于 生产,除非你必须 - 它很昂贵并且很容易导致运行 时间异常

【讨论】:

  • $scope.$apply() 生成错误:'$apply already in progress'。我已经试过了。我会尝试你的想法,在父控制器上公开该方法。
  • 谢谢,我要一直这样下去。如果你想要一个正确的绑定,你必须通过父控制器。
猜你喜欢
  • 2017-12-18
  • 2016-10-03
  • 2020-04-14
  • 2018-02-27
  • 2017-10-23
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
  • 2018-11-23
相关资源
最近更新 更多