使用滤镜Angular js更改ng-model值

时间:2016-10-31 11:44:20

标签: angularjs angular-filters angular-controller

是否可以在输入字段上使用ng-model更新filter值?我有这个文本字段:

<input type="text" ng-model="dateOfJoining" ng-value="dateOfJoining | date:'dd-MM-yyyy'">

ng-model中的

我有这个默认值: - 2016-12-31T18:30:00.000Z并使用过滤器我能够以'dd-MM-yyyy'格式显示格式化的日期值,但我的问题是当我加载另一个视图时属于同一个控制器并返回到此文本字段,然后过滤的值消失,并显示默认值。我想使用ng-model更新filter值,以便我确保正确过滤了值,并且我也可以将过滤后的值发送到服务器。

1 个答案:

答案 0 :(得分:0)

是的,有可能,你只需检查my code in plnkr我认为它可以帮到你

    <!DOCTYPE html>
<html>

  <head>
    <link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
    <script data-require="angular.js@1.2.20" data-semver="1.2.20" src="https://code.angularjs.org/1.2.20/angular.js"></script>
    <script data-require="bootstrap@3.1.1" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script data-require="angular-ui-bootstrap@0.11.0" data-semver="0.11.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <script>
    var myApp = angular.module('myApp', []);



    myApp.controller('myAppCtrl', function($scope) {

     $scope.MyDate = "2016-12-31T18:30:00.000Z";
    });

    angular.module('myApp').directive('formattedDate', function(dateFilter) {
      return {
        require: 'ngModel',
        scope: {
          format: "="
        },
        link: function(scope, element, attrs, ngModelController) {
          ngModelController.$parsers.push(function(data) {
            //convert data from view format to model format
            return dateFilter(data, scope.format); //converted
          });

          ngModelController.$formatters.push(function(data) {
            //convert data from model format to view format
            return dateFilter(data, scope.format); //converted
          });
        }
      }
    });
  </script>
  </head>

  <body ng-app="myApp">
    <div ng-controller="myAppCtrl">


      {{MyDate | date:'medium'}}
      <input type="text" class="form-control" ng-model= "MyDate" formatted-date format="medium" />
    </div>
  </body>

</html>