跨嵌套组件的绑定输出不起作用

时间:2016-05-18 04:28:49

标签: angularjs angularjs-components

今天我一直在讨论这个问题。请。看看下面的代码。你能解释为什么Angular在从第二级组件范围触发onUpdate()方法后会抛出此错误吗?

  

TypeError:无法使用'in'运算符在99

中搜索'$ ctrl'

谢谢!

angular.module('app', [ ]);

angular
  .module('app')
  .controller('appController',function($scope){
    var $ctrl = this;
    
    $ctrl.onUpdate = function(number){
      $ctrl.number = number;
    };       
  })
  
  // Firstlevel
  
  .component('firstLevel', {
    bindings : {
      onUpdate : '&'
    },
    controller: function($scope){   
      var $ctrl = this;
      
      $ctrl.otherStuff = 'other-stuff';

    },
    template : `
      <second-level data-on-update="$ctrl.onUpdate(number)"></second-level>
      `
  })
  
  // second-level
  
  .component('secondLevel', {
    bindings : {
      onUpdate : '&'
    },
    controller: function($scope){
      var $ctrl = this;
			
      $ctrl.save = function(newVal){
      	$ctrl.onUpdate({number:newVal})
      };
    },
    template : `
    	<button ng-click="$ctrl.save(99)">Save 99</button>
      `
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<div ng-app="app" ng-controller="appController as $ctrl">

<div>
# from second level: {{$ctrl.number}}
</div>

<first-level
  data-on-update="$ctrl.onUpdate(number)">    
  </first-level>
</div>

1 个答案:

答案 0 :(得分:1)

试试这个

angular.module('app', [ ]);

angular
  .module('app')
  .controller('appController',function($scope){
    var $ctrl = this;
    
    $ctrl.onUpdate = function(number){
      $ctrl.number = number;
    };       
  })
  
  // Firstlevel
  
  .component('firstLevel', {
    bindings : {
      onUpdate : '&'
    },
    controller: function($scope){   
      var $ctrl = this;
      
      $ctrl.otherStuff = 'other-stuff';

    },
    template : `
      <second-level data-on-update="$ctrl.onUpdate({number: number})"></second-level>
      `
  })
  
  // second-level
  
  .component('secondLevel', {
    bindings : {
      onUpdate : '&'
    },
    controller: function($scope){
      var $ctrl = this;
			
      $ctrl.save = function(newVal){
      	$ctrl.onUpdate({number:newVal})
      };
    },
    template : `
    	<button ng-click="$ctrl.save(99)">Save 99</button>
      `
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<div ng-app="app" ng-controller="appController as $ctrl">

<div>
# from second level: {{$ctrl.number}}
</div>

<first-level
  data-on-update='$ctrl.onUpdate({number: number})'>    
  </first-level>
</div>