我正在尝试根据用户输入更新模型。我有几个(在1到x之间变化的数字)子指令在这里标记为A,B和C,它们只是同一实体的副本。控制器在MAIN页面元素(具有自己的输入)上定义,然后也注入到每个子指令中。

到目前为止,问题在于所有子指令都共享相同的控制器和模型,从而导致其输入彼此覆盖。

如果我在每个子指令中分别定义控制器,则存在在一个控制器内部收集所有数据的问题。

TL; DR:我不确定如何使用MAIN输入元素和子指令(A,B,C)输入元素更新我的模型,同时又保持添加/删除x子指令数量的灵活性。

我感谢您可能有任何文章或建议。我也对替代方法持开放态度。

主要模板:

<div ng-controller="myController as mainCntrl">
    <input type="text" ng-model="mainCntrl.formdata.page_title"></input>
    <div id="container">
        <child-directive cntrl="mainCntrl"></child-directive> /*gets added here dynamically*/
        <child-directive cntrl="mainCntrl"></child-directive>
    </div>
    <button type="submit" ng-click="mainCntrl.submit()">Submit</button>
</div>


主控制器:

     .controller('myController', function ($scope) {
            this.formdata = {
                 page_title: "",
                 objects: {}
            };
            this.submit = function() {
                console.log(this.formdata);
            }

    })


子指令定义:

    .directive("childDirective", function() {
        return {
            restrict: "E",
            scope: {
                cntrl: "="
            },
            templateUrl: 'templateurl',
        }
    })


子指令模板:

<div>
    <input type="text" ng-model="cntrl.formdata.objects.title"></input>
    <textare ng-model="cntrl.formdata.objects.description"></textarea>
</div>


并可视化:

javascript - Angular-将父 Controller 注入(inject)几个子指令-LMLPHP

最佳答案

那呢,只是一个想法:

将对象更改为数组。

.controller('myController', function ($scope) {
        this.formdata = {
             page_title: "",
             objects: []
        };
        this.submit = function() {
            console.log(this.formdata);
        }

})


创建一个将其模型推送到对象数组的子控制器:

.directive("childDirective", function() {
    return {
        restrict: "E",
        scope: {
            cntrl: "="
        },
        templateUrl: 'templateurl',
        controller: ChildCntrl,
        controllerAs: 'vm'
    }
})

ChildCntrl.$inject = ['$scope'];
function ChildCntrl($scope) {
    var vm = this;
    vm.model = {
        title: null,
        description: null
    };
    $scope.cntrl.formdata.objects.push(model);
}


在您的儿童指导模板中使用模型:

<div>
    <input type="text" ng-model="vm.model.title"></input>
    <textare ng-model="vm.model.description"></textarea>
</div>

09-17 11:32