AngularJS 中从对象到 ng-repeat 的绑定指令

Binding directive from object to ng-repeat in AngularJS

我正在使用带有 ng-repeat 的指令,它看起来像这样:

<new-tax-country  
    ng-repeat="newItem in data.company.extraTaxCountries track by $index" 
    ng-model="data.company.extraTaxCountries[$index]"> 
</new-tax-country>

我根据需要在数组中添加对象,像这样:

$scope.addTaxCountry = function() {
   $scope.data.company.extraTaxCountries.push({});
}

每次单击按钮时,我都会向数组中添加一个新的空对象,同时还会创建一个新指令。

我需要将指令绑定到空对象,这样当我填充指令中的字段时,那些字段也存在于之前的空对象中。

到目前为止,我的指令如下所示:

(function() {

    angular.module('account-form-client-de')
        .directive("newTaxCountry", function(Countries) {
            var options = {
                restrict: 'E',
                require: 'ngModel',
                replace: true,
                scope: {
                    
                },
                link: function(scope, element, attrs, controller, $parent) {
                        
                    
                },
                templateUrl: 'template/directive/new-tax-country.html'
            };

            return options;
        });
})();

和 html:

<div class="newtaxcountry">
    <label for="new_taxid">
        bla
    </label>
    <input name="new_taxid" ng-model="newTaxInnerScope.new_taxid">
</div>

我怎样才能让每个 newItem in data.company.extraTaxCountries 自动继承指令中存在的 newTaxInnerScope 对象的属性?

您需要设置双向绑定,以便从内部指令中读取和写回您的变量。

我创建了一个fiddlehttps://jsfiddle.net/aemw7d29/1/

主要部分是这样的:

angular.module('account-form-client-de')
    .directive("newTaxCountry", [function(Countries) {
        function link(scope, element, attrs, controller, $parent) {
            scope.ngModel.a = scope.ngModel.a ? scope.ngModel.a++ : 1;
        }
        
        var options = {
            restrict: 'E',
            require: 'ngModel',
            replace: true,
            scope: { ngModel : '=' },
            link: link,
            template: '<div class="newtaxcountry"><label for="new_taxid">bla</label><input name="new_taxid" ng-model="newTaxInnerScope.new_taxid">{{ngModel}}</div>'
        };

        return options;
    }]);

虽然有公认的答案,但我会把它留在这里...

首先,如果您需要指令的简单输入——永远不要将其命名为 ng-model(您也不需要 require ngModel 指令),只需使用任何其他名称,例如country 这里:

<new-tax-country
  ng-repeat="country in data.company.extraTaxCountries track by $index" 
  country="country">
</new-tax-country>


.directive("newTaxCountry", [function(Countries) {
    var options = {
        restrict: 'E',
        replace: true,
        scope: { country : '=' },
        template: '<div class="newtaxcountry"><label for="new_taxid">bla</label><input name="new_taxid" ng-model="country.new_taxid"></div>'
    };
    
    return options;
}]);

如果您想将此指令放入某种形式并在其上指定验证器(而不是在带下划线的输入元素上),您可能需要使用 ng-model,然后您需要 ngModelCtrl 并使用它而不是范围绑定.