2017-06-14 105 views
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>