AngularJS Binded模型选择更新输入数字字段,最小最小值

时间:2013-12-15 12:05:07

标签: javascript angularjs

非常令人困惑,因为我尝试了很多方法并且看起来都很混乱。

视图

<select ng-model="somemodel" ng-options="val as val.name for val in vals" ng-init="somemodel=vals[2]"></select>
<input type="number" ng-model="somemodel.value" min="{{somemodel.min}}" max="{{somemodel.max}}">
{{somemodel.value}}

控制器

function appCtrl($scope) {
$scope.somemodel = "";
$scope.vals = [
  {name:"a", min:"1", max:"10", value:4},
  {name:"b", min:"10", max:"20", value:14},
  {name:"c", min:"21", max:"31", value:24},
  {name:"d", min:"31", max:"41", value:34}];
}

当我更改选择时,它会更新模型,但不会更新输入。然而,如果我更改输入,它也会更新模型。如何选择以AngularJS方式更新输入视图?

这里展示了这种情况:http://jsfiddle.net/rq8qs/4/

更新:更新小提琴

update2:将值更改为数字类型

替代方法 http://jsfiddle.net/rq8qs/10/

2 个答案:

答案 0 :(得分:3)

由于验证器在角度核心中的实现方式,这可能是一个(目前至少是)无法解决的问题。我认为伪造这种行为是你最好的选择。为此,以下方法可行:

<input
  ng-model="v.value"

  ng-repeat="v in values"
  ng-if="v == selected"

  type="number"
  min="{{v.min}}"
  max="{{v.max}}"
>

演示:http://jsbin.com/AmOHoHa/2/

答案 1 :(得分:0)

我为此写了一个简单的指令。

工作演示:http://plnkr.co/edit/BJ98ZR?p=preview

.directive('validateRange', ['$parse', function($parse) {

    function link($scope, $element, $attrs, ngModel) {
        var attrRange, range = [];

        function validate(value) {
            var validMin = true, validMax = true;
            if (typeof range[0] === 'number') {
                ngModel.$setValidity('min', value >= range[0]);
                validMin = value >= range[0];
            }
            if (typeof range[1] === 'number') {
                ngModel.$setValidity('max', value <= range[1]);
                validMax = value <= range[1];
            }
            return validMin && validMax ? value : undefined;
        }

        attrRange = $attrs.validateRange.split(/,/);

        range[0] = $parse(attrRange[0] || '')($scope);
        range[1] = $parse(attrRange[1] || '')($scope);

        $scope.$watchCollection('[' + $attrs.validateRange + ']', function(values) {
            range = values;
            validate(ngModel.$viewValue);
        });

        ngModel.$parsers.unshift(validate);
        ngModel.$formatters.unshift(validate);
    }

    return {
        link: link,
        require: 'ngModel'
    };

}]);

<form name="myform" ng-init="minvalue=0;value=1;maxvalue=2">
    Min Value:
    <input type="number" name="minvalue" required
           data-validate-range="0,value"
           ng-model="minvalue">

    Value:
    <input type="number" name="value" required
           data-validate-range="minvalue,maxvalue"
           ng-model="value">

    Max Value:
    <input type="number" name="maxvalue" required
           data-validate-range="value,false"
           ng-model="maxvalue">

    <pre>
        myform.minvalue.$error {{ myform.minvalue.$error }}
        myform.value.$error    {{ myform.value.$error }}
        myform.maxvalue.$error {{ myform.maxvalue.$error }}
    </pre>
</form>