0

僅更新「視圖」的值,所以我有這樣在控制器中的十進制值:使用角指令

// 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.percentValue0.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 
    }; 
}; 

請指教!

+0

嘗試使用過濾器代替。 – Claies

+1

@KimchiMan,你已經在使用'$ formatters'來轉換模型表示以便顯示,所以只需簡單地定義一個'$ parsers'就可以以另一種方式來完成它,就像so-http://plnkr.co/edit/ lB6GaT1ZSrVsOi9PS1u9?p =預覽 – miqid

+0

@miqid,你的回答正是我想要的 - 你能在答案部分添加代碼嗎?我將它標記爲答案 –

回答

1

包括作爲一個答案我的意見,因爲它似乎幫助。 :-)

總結:既然你已經爲你的指令,該模型值($modelValue)轉換成顯示的形式($viewValue)提供的$formatters功能,它只是提供了一個$parsers功能做的事反轉並將任何用戶輸入轉換回模型值。

Example Plunker

0

你試圖達到的是可能可能,但我會發現它閱讀代碼真的很混亂。我認爲解決問題並保持可讀性的最簡單的解決方案是在$scope.percentValue中存儲整數值(5),以便在鍵入並顯示<input>中的值時ng-model總是處理整數。然後創建一個custom filter並使用它在<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> 
0

我想創建爲百分比過濾器:

angular.module('myModule') 
.filter('percentage', ['$filter', function($filter) { 
    return function(input, decimals) { 
     return $filter('number')(input*100, decimals)+'%'; 
    }; 
}]); 

的投入將存儲整數(如5)

<input ng-model="percentValue" /> 

但我會添加一個過濾器,以跨度部分:

<span>{{percentValue | percentage:2}}</span> 

感謝https://stackoverflow.com/a/21727765/3687474的過濾指令。

0

除了創建一個過濾器,你還可以計算在模板

<span>{{percentValue * 100}}</span>