组件不会对其控制器的范围更改做出反应

时间:2016-05-15 13:48:43

标签: angularjs

我有两个使用require进行通信的简单组件。问题是函数中更改的变量未反映在组件视图中。请参阅下面的示例。

<wizard-element data-active="true">First
      <wizard-test></wizard-test>
  </wizard-element>
  <wizard-element>Second
    <wizard-test></wizard-test>
  </wizard-element>

组件很简单,通过单击取消激活,向导元素应该是不可见的,但它不是。

Wizard-element是一个负责显示和隐藏的包装器组件。向导测试具有按钮以显示或隐藏,并通过require与wizard-element进行通信。

component('wizardElement',{
        transclude: true,
        controller: ['$scope',function($scope){

            this.activate = function(){
                console.log('show');
                this.active = true;
            }

            this.disactivate = function(){
                console.log('hide');
                $scope.active = false;
            }
        }],
        
        bindings: {
            'active': '=',
            'step': '<'
        },
        template: '<div ng-show="$ctrl.active" ng-transclude></div>'
})
.component('wizardTest',{
        controller: ['$scope',function($scope){

            this.activate =  function(){
              this.wizardElement.activate();
            }
            
            this.disactivate =  function(){
              this.wizardElement.disactivate();
            }
        }],
        require: {
          'wizardElement' : '^^wizardElement'    
        },
        template: '<button ng-click="$ctrl.activate()">Activate</button><button ng-click="$ctrl.disactivate()">Disactivate</button>'
});

链接到Plunker https://plnkr.co/edit/A5Hl1qYDhaMTgvvuIS11?p=preview

2 个答案:

答案 0 :(得分:0)

您正在$scopethis函数中混合使用activate()disactivate()

尝试更改

this.disactivate = function() {
  console.log('hide');
  $scope.active = false;
}

this.disactivate = function() {
  console.log('hide');
  this.active = false;
}    

答案 1 :(得分:0)

Plunker示例在之前的建议之后有效但我的应用程序并不像我认为的那样。方法 activate disactivate 被调用,但不会更改视图。我还在向导元素模板中转储{{$ ctrl}}以查看范围,但活动值不会更改。

<wizard>
    <wizard-element data-step="1" data-active="true" >First Step</wizard-element>
    <wizard-element data-step="2" >Second step</wizard-element>
    <button class="btn border-only center-block margin-top" wizard-next-control>Next</button>

我的JS:

    authApp.component('wizardElement',{
    transclude: true,
    controller: ['$scope','$timeout',function($scope,$timeout){

        this.active = this.active || false;

        this.$onInit = function() {
            this.wizardCtrl.addElement(this, this.step);
        }
        this.activate = function(){
            console.log('show', this.step);
            this.active = true;
        }

        this.disactivate = function(){
            console.log('hide', this.step);
            this.active = false;
        }
    }],
    require:{
        'wizardCtrl' : '^^wizard',
    },
    bindings: {
        'step': '<'
    },
    template: '<span>val:{{$ctrl}}</span><div ng-show="$ctrl.active"><ng-transclude></ng-transclude></div>'});