无法使用angularjs设置双向绑定

时间:2017-02-14 10:50:40

标签: html angularjs binding

这是我的父亲组件

(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

为什么会这样?

1 个答案:

答案 0 :(得分:0)

首先,要避免这些问题只需修改子对象,不要创建新对象。对于数组,只需将长度设置为0并添加新元素。

  1. 什么是'='?您告诉这是同一个对象,因此chil.propertyparent.property指向同一个对象。
  2. 现在你说chil.property = anotherObject。 Angular仍然是javascript,因此无法修改parent.property。现在这两点指出了不同的对象。
  3. 现在$digest将运行 - 这将被修复,他们将指向新对象。示范:
  4. 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