我刚刚开始与AngularJS一起玩,并试图了解绑定技巧。对于初学者,我试图做一个简单的转换计算器(几十个到几个,几十个)。这很好,但是当我尝试将范围输入和数字输入绑定到相同的模型属性时,在调整范围值时,输入的数字不会更新。我有一个jsfiddle显示行为:
常见的JavaScript为破碎和工作的fiddles:
var myApp = angular.module('myApp',[]); myApp.controller('CalcCtrl',function ($scope) { var num = 0.0; $scope.qty = new Quantity(12); $scope.num = num; }); function Quantity(numOfPcs) { var qty = numOfPcs; var dozens = numOfPcs / 12; this.__defineGetter__("qty",function () { return qty; }); this.__defineSetter__("qty",function (val) { qty = val; dozens = val / 12; }); this.__defineGetter__("dozens",function () { return dozens; }); this.__defineSetter__("dozens",function (val) { dozens = val; qty = val * 12; }); }
HTML:
<div ng-controller="CalcCtrl"> <form> <label for="pcs">Pieces:</label> <input type="number" min="0" ng-model="qty.qty" size="20" id="pcs" /> <input type="range" min="0" max="100" ng-model="qty.qty" /> <br/> <label for="numOfDozens">Dozens</label> <input type="number" min="0" ng-model="qty.dozens" size="20" id="numOfDozens" /> </form> </div>
然而,将两个数字输入绑定到相同的模型属性似乎可以正常工作,如这个小提示:
HTML:
<div ng-controller="CalcCtrl"> <form> <label for="pcs">Pieces:</label> <input type="number" min="0" ng-model="qty.qty" size="20" id="pcs" /> <input type="number" min="0" max="100" ng-model="qty.qty" /> <br/> <label for="numOfDozens">Dozens</label> <input type="number" min="0" ng-model="qty.dozens" size="20" id="numOfDozens" /> </form> </div>
这里的问题是输入类型=“范围”与字符串不匹配,而不是数字(而输入类型=“数字”仅适用于数字)。
http://www.w3.org/wiki/HTML/Elements/input/range
The range state represents a control for setting the element’s value to
a string representing a number.
如果您添加val = parseInt(val)作为您的第一个指令在数量设置器应该工作:
this.__defineSetter__("qty",function (val) { val = parseInt(val); qty = val; dozens = val / 12; });
jsfiddle:http://jsfiddle.net/bmleite/2Pk3M/2/