Benjamin Li Benjamin Li - 1 month ago 6
AngularJS Question

Angular, change variable value in run block

I have a run block, the code is

.run(['$rootScope', 'formlyConfig', 'appApiCheck', 'licenseExpDateValue',
($rootScope, formlyConfig, appApiCheck, licenseExpDateValue) => {

$rootScope.maskPlaceHolder = '';

formlyConfig.setType({
name: 'maskedInput',
extends: 'input',
template: '<input class="form-control" ng-model="model[options.key]" ng-required="{{licenseExpDateValue.required}}" ng-class="{\'has-error\':licenseExpDateValue.showError}"/>',
defaultOptions: {
ngModelAttrs: {
mask: {
attribute: 'ui-mask'
},
maskPlaceholder: {
attribute: 'ui-mask-placeholder'
}
},
templateOptions: {
maskPlaceholder: $rootScope.maskPlaceholder
}
}
})
}])


and later, I will fetch the data from server, and will change
$rootScope.maskPlaceholder
, but
maskPlaceholder
in
templateOptions
is still the same.

how to update the
maskPlaceHolder
of
templateOptions
?

thanks

2ps 2ps
Answer

I would do this with a one-time watcher. Something like

.service('UpdateConfig', [ '$rootScope', 'formlyConfig', function ($rootScope, formlyConfig) {
  var x = {
    updateConfig: function (maskPlaceHolder) {
      formlyConfig.setType({
        name: 'maskedInput',
        extends: 'input',
        template: '<input class="form-control" ng-model="model[options.key]" ng-required="{{licenseExpDateValue.required}}" ng-class="{\'has-error\':licenseExpDateValue.showError}"/>',
        defaultOptions: {
          ngModelAttrs: {
            mask: {
              attribute: 'ui-mask'
            },
            maskPlaceholder: {
                attribute: 'ui-mask-placeholder'
            }
          },
          templateOptions: {
            maskPlaceholder: maskPlaceholder
          }
        }});
    },
    watcher: $rootScope.$watch('maskPlaceHolder', function (value) {
        x.updateConfig(value);
        x.watcher();
    });
  };
  return x;
}])
.run(['$rootScope', 'UpdateConfig', 'appApiCheck', 'licenseExpDateValue',
    ($rootScope, UpdateConfig, appApiCheck, licenseExpDateValue) => {      
    UpdateConfig.update('');
});