2017-02-14 10 views
0

を使用して双方向のバインディングを設定することができない私の父コンポーネントはここangularjs

(function (app) { 
    app.component('voiceFormComponent', { 
     templateUrl: 'partials/voice-form.html', 
     controller: ['$state', '$stateParams', '$http', 'updateService', 'uploadService', 'countriesService', 'flagsService', 
      function ($state, $stateParams, $http, updateService, uploadService, countriesService, flagsService) { 

       var self = this; 
       console.log("in voice prompt component"); 

       self.filesToUpload = []; 


       self.submit = function() { 
        if (self.filesToUpload.length > 0) { 
          self.uploadFiles(); 
        } 
       ... 

とそのhtmlです:

      <!--upload files--> 
          <upload-files-component voice-id="$ctrl.voice.id" files-to-upload="$ctrl.filesToUpload" has-files="$ctrl.hasFiles"></upload-files-component> 
         </div> 

それはそれでコンポーネント

(function (app) { 
    app.component('uploadFilesComponent', { 
     templateUrl: 'partials/upload-files-partial.html', 

     bindings: {filesToUpload: '='}, 
     controller: ['$scope', function ($scope) { 

      var self = this; 

      $scope.$watch('files.length', function (newVal, oldVal) { 
       console.log($scope.files); 
       this.filesToUpload = $scope.files; 
      }); 
     }] 
    }) 
})(promptoWeb); 
と結合する2つの方法があります

どうすればson-componentにself.filesToUploadが埋め込まれますか

しかし、父のコンポーネントのself.filesToUpload.length === 0

なぜですか?

答えて

0

まず、これらの問題を回避するには、子供のオブジェクトを変更するだけで、新しいものを作成しないでください。配列の場合、長さを0に設定して新しい要素を追加するだけです。

  1. 「=」とは何ですか?これは同じオブジェクトであると言うので、chil.propertyparent.propertyは同じオブジェクトを指しています。
  2. 今、あなたはchil.property = anotherObjectと言っています。角度はまだusuallのjavascriptですので、これは変更できませんparent.property。今、これらの2つの異なるオブジェクトを指します。
  3. $digestを実行すると、これが修正され、新しいオブジェクトを指し示します。デモンストレーション:
app.controller('MainCtrl', function($scope, $timeout) { 
    $scope.twoway = 'initial'; 

    $scope.callback = function(param) { 
    console.log('child value: ' + param); 
    console.log('parent value: ' + $scope.twoway); 
    $timeout(function() { 
     console.log('parent value after digest: ' + $scope.twoway); 
    }); 
    } 
}); 

app.component('test', { 
     template: '<div></div>', 

     bindings: {twoway: '=', callback: '&'}, 
     controller: ['$timeout', function ($timeout) { 

      var self = this; 

      $timeout(function() { 
       self.twoway = 'new'; 
       self.callback({param: self.twoway}); 
      }) 
     }] 
    }) 

出力:

child value: new 
parent value: initial 
parent value after digest: new 

http://plnkr.co/edit/5K7CtsL0Bnp3RfuM30ac?p=preview

関連する問題