0

在 Angular (1.4.x) 中,有没有办法在不更改 $modelValue 的情况下动态更改输入上下文?例如:是否可以在不更改 $modelValue. 这是一个将同时更改视图和模型值的示例。我只需要屏蔽输入上下文而不是模型值。

谢谢!

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>

4

1 回答 1

1

你真的很亲近。

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');
}
}
}
});
于 2016-03-24T09:43:30.733 回答