0

In Angular (1.4.x), is the there a way to dynamically change the input context without changing the $modelValue? So for example: is it possible to dynamically toggle a time (moment) input text/content for local/utc without changing the $modelValue. Here's an example that will change both view and model values. I just need to mask the input context and not the model value.

Thanks!

var app = angular.module('testparser', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = {
    name: ''
  };
});
app.directive('changetime', function() {
  return {
    restrict: 'EA',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      //format text going to user (model to view)
      ngModel.$formatters.push(function(value) {
        return value;
      });

      //format text from the user (view to model)
      ngModel.$parsers.push(function(value) {
        return value;
      });

      scope.data.time = moment().format('HH:mm:ss')
      scope.setLocalTime = function() {
        scope.data.time = moment().local().format('HH:mm:ss');
      }
      scope.setUtcTime = function() {
        scope.data.time = moment().utc().format('HH:mm:ss');
      }
    }
  }
});
<html ng-app="testparser">

<head>
  <meta charset="utf-8" />
  <script data-require="angular.js@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
  <script data-require="moment.js@*" data-semver="2.10.2" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>


</head>

<body ng-controller="MainCtrl">
  <input type="button" value="set to local" ng-click="setLocalTime()" />
  <input type="button" value="set to utc" ng-click="setUtcTime()" />
  <input changetime ng-model="data.time" />
  <pre>model is: {{data.time}}</pre>
</body>

</html>
user2994871
  • 177
  • 2
  • 13

1 Answers1

1

You were really close.

var app = angular.module('testparser', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = {
    name: ''
  };
});

app.directive('changetime', function() {
return {
    restrict: 'EA',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
  //format text going to user (model to view)
  ngModel.$formatters.unshift(function(value) {
    return value;
  });

  //format text from the user (view to model)
  ngModel.$parsers.unshift(function(value) {
    return value;
  });

  scope.data.time = moment().format('HH:mm:ss')

  scope.setLocalTime = function() {
    ngModel.$viewValue = moment().local().format('HH:mm:ss');
    ngModel.$render();
    //scope.data.time = moment().local().format('HH:mm:ss');
}
scope.setUtcTime = function() {
    ngModel.$viewValue = moment().utc().format('HH:mm:ss');
    ngModel.$render();
    //scope.data.time = moment().utc().format('HH:mm:ss');
}
}
}
});
Kalimero95
  • 43
  • 1
  • 9