Raphael
Raphael

Reputation: 11

angular custom directive two way binding issue

I've seen some examples online and some answered questions here at SO, but somehow, I'm not getting a two-way binding on my custom directive.

When I change the input value that is inside my directive's template, the ngModel doesn't update on the controller's scope.

Here's what I have:

Controller

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

Directive

.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
            };
        }
    }
});

Template

<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>

and finally, the HTML with the custom directive

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

Upvotes: 0

Views: 470

Answers (1)

wajid baba
wajid baba

Reputation: 41

I think problem is with controller varaible,once pass your controller variable as object instead of direct variable like this,

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

and in HTML use:

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

Hope this will work.

Upvotes: 0

Related Questions