2013-04-09 67 views
11

我在Angular JS中創建自定義指令。我想在模板呈現之前格式化ng模型。AngularJS - 在自定義指令中呈現模板之前格式化ng模型

這是我到目前爲止有:

app.js

app.directive('editInPlace', function() { 
    return { 
     require: 'ngModel', 
     restrict: 'E', 
     scope: { ngModel: '=' }, 
     template: '<input type="text" ng-model="ngModel" my-date-picker disabled>' 
    }; 
}); 

HTML

<edit-in-place ng-model="unformattedDate"></edit-in-place> 

我想的的ngModel進入之前格式化unformattedDate值模板。這樣的事情:

template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>' 

但這給了我一個錯誤。這個怎麼做?

回答

25

ngModel公開其控制器ngModelController API併爲您提供了一種方法。

在您的指令中,您可以添加$formatters,它們完全符合您的需求,並且可以通過其他方式(在將值傳遞給模型之前對其進行解析)添加$parsers

這是你應該怎麼走:

app.directive('editInPlace', function($filter) { 
    var dateFilter = $filter('dateFormat'); 

    return { 
    require: 'ngModel', 
    restrict: 'E', 
    scope: { ngModel: '=' }, 
    link: function(scope, element, attr, ngModelController) { 
     ngModelController.$formatters.unshift(function(valueFromModel) { 
     // what you return here will be passed to the text field 
     return dateFilter(valueFromModel); 
     }); 

     ngModelController.$parsers.push(function(valueFromInput) { 
     // put the inverse logic, to transform formatted data into model data 
     // what you return here, will be stored in the $scope 
     return ...; 
     }); 
    }, 
    template: '<input type="text" ng-model="ngModel" my-date-picker disabled>' 
    }; 
}); 
+0

你從哪裏弄來$過濾器?是否有必要將它傳遞給函數?我在全局範圍內使用格式化程序來格式化日期。所以我現在的參數是$ rootScope – Lulu 2013-04-09 13:20:52

+0

valueFromModel變量也返回undefined。我做錯了什麼? – Lulu 2013-04-09 13:23:43

+0

'$ filter'是注入的,因爲我以爲你正在使用它。如果沒有,只需注入'$ rootScope'併到達過濾器。關於'valueFromModel',可能在開始時這個值是'null',所以返回'null'或''。 – 2013-04-09 14:53:14

相關問題