jeudi 25 juin 2015

AngularJS Directive does not synchronize back when model is changed

I am working to extend a input directive myAddressPostalCode with an autocompletion functionality. After adding the typeahead functionality, back-synchronization from model (when model field is changed by another directive or service) stopped working. This causes my tests to fail. Any idea what could cause this?

My directive code:

     var secretValue = "$-secret-$";
         
         
         .directive("typeaheadWatchChanges", function() {
      return {
        require: ["ngModel"],
        link: function(scope, element, attr, ctrls) {
          scope.$watch(attr.typeaheadWatchChanges, function(value) {
            if(((ctrls[0].$viewValue === "") || (typeof ctrls[0].$viewValue === "undefined")) && (value.length > 0)) {
              ctrls[0].$setViewValue(secretValue);
            }else{
              ctrls[0].$setViewValue("");
            }
          });
        }
      };
    })
 
 
 .directive('myAddressPostalCode', function () {
      return {
        restrict: 'A',
        require: '^myAddressContainer',
        replace: true,
        scope: true,
        template: '<input ng-model="myAddress.postalCode" ng-blur="myValidateAddress()" my-apply-value my-validation my-validation-identifier="{{myIdentifier}}_postalCode" ' +
        ' typeahead="postalCode for postalCode in postalCodeBindList" ng-focus="onFocusPostalCode()" typeahead-watch-changes="postalCodeBindList"  class="form-control">',
        link: function (scope, element, attrs) {
          scope.postalCodeBindList = [];
          scope.onFocusPostalCode = function() {
            if((scope.myAddress.regionCode) && (scope.myAddress.regionCode === "$-secret-$")){
              scope.myAddress.regionCode = "";
            }

            if((scope.myAddress.postalCode) && (scope.myAddress.postalCode === "$-secret-$")){
              scope.myAddress.postalCode = "";
            }

            return scope.myLookupAddress(attrs.myFastCompletionProfile).
                then(function (addressList) {

                  var postalCodeList = [];
                  addressList.forEach(function (postalCodeItem) {
                    if (postalCodeList.indexOf(postalCodeItem.postalCode) === -1) {
                      postalCodeList.push(postalCodeItem.postalCode);
                    }
                  });
                  if (! (postalCodeList.length === 1 && postalCodeList[0] === scope.myAddress.postalCode)){
                    scope.postalCodeBindList = postalCodeList;
                  }

                 return postalCodeList;
                });
          };
        }
      };
    })

Aucun commentaire:

Enregistrer un commentaire