Angularjs $ viewValue而不更改$ modelValue

时间:2016-01-15 21:43:43

标签: angularjs angularjs-directive angular-ngmodel angular-moment

在Angular(1.4.x)中,是否可以在不更改$ modelValue的情况下动态更改输入上下文?例如:是否可以在不更改$ modelValue的情况下动态切换本地/ utc的时间(时刻)输入文本/内容。这是一个将更改视图和模型值的示例。我只需要屏蔽输入上下文而不是模型值。

谢谢!



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分: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');
}
}
}
});