这是我的父亲组件
(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);
如何在子组件中填充self.filesToUpload
但是父组件中的self.filesToUpload.length === 0
为什么会这样?
答案 0 :(得分:0)
首先,要避免这些问题只需修改子对象,不要创建新对象。对于数组,只需将长度设置为0并添加新元素。
chil.property
和parent.property
指向同一个对象。 chil.property = anotherObject
。 Angular仍然是javascript,因此无法修改parent.property
。现在这两点指出了不同的对象。$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