2016-09-08 15 views
2

별도의 위젯과 같은 구성 요소를 만들기로 결정했습니다. 부모는 config에 전달하고 구성 요소는 데이터를 가져옵니다 (부모는 자식의 데이터가 필요하지 않음). 그러나 일부 경우 (예 : 부모에서 일부 업데이트)가 표시되는 데이터에 영향을 줄 수 있습니다. 그래서 나는 아이에게 일종의 말을하고 싶습니다 : 설정을 그대로 유지하면서 데이터를 다시 가져옵니다. 하지만이 구성 개체에 대한 링크가 동일로, 화재 $onChanges 콜백을 발생하지 않습니다, 그래서 해키 방법으로 해결이 나를 위해로서, 미세하지만 추한 작동각도 1.5 구성 요소 문제

vm.childConfig = _.assign({}, vm.childConfig); 

. 거기에 더 좋은 해결책이 있습니까?

<parent-component> 
     <child-component config="childConfig"></child-component> 
</parent-component> 

JS :

일부 예제 코드 ($ 시계를 생성, 방출 이벤트가 더 악화 솔루션이 될 것 같다) 힘 아이처럼 뭔가 전화를

function ParentComponentController() { 
    vm.childConfig = {show: true, ...} 

    vm.onItemDelete = function() { 
     vm.childConfig = _.assign({}, vm.childConfig); // I want to call `fetchData` so I force child $onChanges to fire. 
    } 
} 

function ChildComponentController() { 
    vm.$onInit = function() { 
     fetchData() 
    } 
    vm.$onChanges = function() { 
     // will not fire if will not change the config object reference 
     fetchData(changes) 
    } 
} 

그래서 내가 원하는 $onChanges

PS 나는 자식이 벙어리 구성 요소 (부모는 가져온 데이터를 전달한다)에 대한 아이디어를 좋아하지 않는다. 물론이 문제를 해결할 것이지만, 그 데이터는 자식에게만 필요하며, 부모 구성 요소가 더 뚱뚱해질 것이다.

+0

당신이 무엇을 요구하고 있는지 명확하지 않습니다. 문제를 나타내는 코드를 보여주십시오. – gyc

답변

1

이게 당신이 의미하는 것입니까?

ChildComponent

this.$onChanges = function() { 
     if (angular.isDefined(this.config) && !init) { 
      init(); 
     } 
     else if (angular.isDefined(this.update) && update) { 
      update(); 
     } 
    }; 
: -

JS

angular.module("app") 
    .component(
     "ChildComponent", 
     { 
      controller: ChildComponentCtrl, 
      bindings: { 
       config: "<", 
       update: "<" 
      } 
     } 
    ); 


function ChildComponent() { 
    var init = false; 

    function init() { 
     // Set up config 
     init = true; 
    } 

    function update() { 
     // config remains the same but do something else 
    } 

    this.$onChanges = function() { 
     if (angular.isDefined(this.config) && !init) { 
      init(); 
     } 
     else if (angular.isDefined(this.update)) { 
      update(); 
     } 
    }; 
} 

마크 업

<parent-component> 
    <child-component config="childConfig" update="update"></child-component> 
</parent-component> 

편집 확인 업데이 트를 만들려면 한 번 다음과 같이 이상 작동

부모 구성 요소

function doUpdate() { 
    this.update = true; 
    // Rest update so that it works next time 
    $timeout(function() { 
     this.update = false; 
    }); 
} 
+0

이것은 처음으로 작동하는 것으로 보이지만 두 번째로 자식을 업데이트해야하는 경우 'update'플래그를 'true'로 설정하면 작동하지 않습니다 ($ onChanges가 실행되지 않음). –

+0

@SergeyVorobey 편집을 참조하십시오. –

관련 문제