【问题标题】:angular custom directive two way binding issue角度自定义指令两种方式绑定问题
【发布时间】:2015-07-07 19:25:51
【问题描述】:

我在 SO 上看到了一些在线示例和一些已回答的问题,但不知何故,我的自定义指令没有得到双向绑定。

当我更改指令模板中的输入值时,ngModel 不会在控制器的范围内更新。

这是我所拥有的:

控制器

$scope.tpcompl = "default value";
$scope.$watch('tpcompl', function(val) {
    alert('value changed!');
});

指令

.directive("panMdAutocomplete", function() {
    return {
        restrict: 'E',
        scope: {
            ngModel: '=panModel',
            panLista: '=',
            panLabel: '=',
            panMaxlength: '=',
            panFlex: '='
        },
        templateUrl: 'template.html',
        link: function($scope, element, attrs){
            var sugereItem = function(termo) {
                var valor = termo.toUpperCase().trim();
                var resultados = [];
                for (var i=0;i<$scope.panLista.length;i++) {
                    var item = $scope.panLista[i];
                    if (item.id.toUpperCase().indexOf(valor) !== -1) {
                        resultados.push({label:item.id, value:item.id});
                    }
                }
                return resultados;
            }

            $scope.autocomplete_options = {
                    suggest: sugereItem
            };
        }
    }
});

模板

<span mass-autocomplete>
    <md-input-container ng-class="{'md-input-has-value': ngModel}" flex="{{panFlex}}" style="position:static;">
        <label>{{panLabel}}</label>
        <input type="text" ng-model="ngModel" ng-attr-maxlength="{{panMaxlength ? panMaxlength : ''}}" mass-autocomplete-item="autocomplete_options" class="md-input">
    </md-input-container>
</span>

最后是带有自定义指令的 HTML

<pan-md-autocomplete pan-lista="tiposcompl" pan-label="'Complemento'" pan-maxlength="'8'" pan-flex="'25'" pan-model="tpcompl"></pan-md-autocomplete>

【问题讨论】:

  • 什么是md-input-container?和mass-autocomplete?
  • 在这个plunker 中似乎一切正常。您可以更改它以重现您的问题吗?
  • 嗨,格兰迪,感谢您的回复! md-input-container 是 angular-material 模块和 angular-mass-autocomplete 的 mass-autocomplete 的一部分。我认为问题在于大规模自动完成创建了一个新范围并破坏了模型流程。无论如何,我已经更改了代码,现在将使用 angular-material 的自动完成指令。我正在考虑调整它以适应一些需求,但我认为它现在就可以了。再次感谢!

标签: javascript angularjs angularjs-directive angularjs-scope


【解决方案1】:

我认为问题在于控制器变量,一旦将控制器变量作为对象而不是像这样的直接变量传递,

  $scope.tpcompl = {
               value :"default value"
                    };

在 HTML 中使用:

<pan-md-autocomplete pan-lista="tiposcompl" pan-label="'Complemento'" pan-maxlength="'8'" pan-flex="'25'" pan-model="tpcompl.value"></pan-md-autocomplete>

希望这会奏效。

【讨论】:

    猜你喜欢
    • 2013-09-23
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2015-04-17
    相关资源
    最近更新 更多