2017-02-14 1 views
0

hier ist mein Vater Komponentekann nicht eingestellt Zweiweg-Bindungen 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(); 
        } 
       ... 

und seine html mit:

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

es hat einen 2-Wege mit einer Komponente darin Bindung

(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); 

wie kommt die self.filesToUpload ist in der son-komponente

012 gefüllt

aber self.filesToUpload.length === 0 in der Vaterkomponente

warum ist das?

Antwort

0

Zuerst, um diese Probleme zu vermeiden, nur Objekt in Kind ändern, nicht neu erstellen. Setzen Sie für ein Array einfach die Länge auf 0 und fügen Sie neue Elemente hinzu.

  1. Was ist '='? Sie sagen, dass dies das gleiche Objekt ist, also haben Sie chil.property und parent.property zeigt dasselbe Objekt.
  2. Jetzt sagen Sie chil.property = anotherObject. Angular ist immer noch JavaScript, so kann dies parent.property nicht ändern. Jetzt zeigen diese zwei verschiedene Objekte.
  3. Jetzt, wenn $digest wird ausgeführt - das wird behoben werden und sie werden neue Objekt zeigen. Demonstration:
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}); 
      }) 
     }] 
    }) 

Ausgang:

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

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

Verwandte Themen