[英]Updating only the 'view' value using angular directive
所以我在控制器中有一個十進制值,如下所示:
// Controller
var MyController = function($scope) {
...
$scope.percentValue = 0.05; // can be stored
...
};
<!-- View -->
<span>{{percentValue}}</span>
<input ng-model="percentValue" />
使用上面的代碼, input
元素中的值是0.05
但是,我想允許用戶輸入一個像5
這樣的整數值。
因此,如果$ scope.percentValue為0.05
,我想在輸入元素中將其顯示為5
。 如果用戶輸入5
,則$ scope.percentValue應該為0.05
。
但是,這里棘手的事情是我只想更新視圖值 -這意味着span
元素仍應顯示0.05
。 僅輸入元素中的值應為5
。
我正在嘗試使用ngModel來實現這一點 ,但我仍在努力。
這就是我現在所擁有的:
var MyDirective = function() {
function link(scope, element, attrs, ngModel) {
ngModel.$render = function() {
element.val(ngModel.$viewValue || '');
};
ngModel.$formatters.push(function (value) {
return value * 100;
});
element.on('change blur', function() {
ngModel.$setViewValue(element.val());
});
}
return {
restrict: 'A',
require: '?ngModel',
scope: {},
link: link
};
};
請指教!!
將我的評論作為答案,因為它似乎有所幫助。 :-)
概括地說:由於您已經為指令提供了$formatters
函數,該函數將模型值( $modelValue
)轉換為顯示形式( $viewValue
),因此只需提供$parsers
函數來進行反向轉換即可任何用戶輸入回到模型值。
您試圖實現的目標可能是可能的,但是我會發現閱讀代碼確實令人困惑。 我認為可以解決您的問題並保持可讀性的最簡單解決方案是在$scope.percentValue
存儲一個整數值( 5
),以便ng-model
在<input>
鍵入和顯示值時始終處理整數。 。 然后創建一個自定義過濾器,並使用它在<span>
中將值輸出為0.05
。
編輯:添加一個具體的代碼示例。 在這里玩: https : //plnkr.co/edit/C1cX2L9B2GM2yax1rw7Z?p=preview
JS:
var MyController = function ($scope) {
$scope.percentValue = 5;
};
function formatPercent (input) {
return input / 100;
}
var myApp = angular.module('MyApp', []);
myApp.filter('percent', function () { return formatPercent });
myApp.controller('MyController', ['$scope', MyController]);
HTML:
<body ng-controller="MyController">
<span>{{ percentValue | percent }}</span>
<input ng-model="percentValue">
</body>
我將為百分比創建一個過濾器:
angular.module('myModule')
.filter('percentage', ['$filter', function($filter) {
return function(input, decimals) {
return $filter('number')(input*100, decimals)+'%';
};
}]);
輸入將存儲整數(例如5)
<input ng-model="percentValue" />
但我將在span部分添加一個過濾器:
<span>{{percentValue | percentage:2}}</span>
記入https://stackoverflow.com/a/21727765/3687474作為filter指令。
除了創建過濾器之外,您還可以在模板上進行計算
<span>{{percentValue * 100}}</span>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.