0
HTMLのサイズを縮小し、将来変更しやすくするために、JSONファイルからラベル/入力情報をインポートしています。これは、ngModelの文字列入力を使用していることを意味します。ngModel用のAngularJS文字列
問題は、双方向バインディングが期待どおりに動作していないことです。私はディレクティブがこれを助けるために使用されるいくつかのスレッドを見てきましたが、動作させることができません。
フィドル例:http://jsfiddle.net/kelh/LLuwka8h/
編集:フィドル例更新:http://jsfiddle.net/kelh/6vccr206/
"第二" "第1" からselectタグを変更すること、2番目のテキストボックスを変更する(文字列入力)はnum2の正しい値にバインドされませんが、代わりにnum1が変更されます。
JSコード:
var app = angular.module('myApp',[]);
app.controller('MyCtrl', ['$scope', function($scope)
{
$scope.calc = {num1:100, num2:350};
$scope.num1 = 100;
$scope.num2 = 350;
$scope.labels = {
selected: null,
options: [
{id: 0, name: 'first'},
{id: 1, name: 'second'}
]
};
$scope.labels.selected = $scope.labels.options[0];
$scope.itemsPlaceholder = [{"label":"First One", "model":"calc.num1"}, {"label":"Second one", "model":"calc.num2"}];
$scope.items = [$scope.itemsPlaceholder[0]];
$scope.change = function()
{
var id = $scope.labels.selected.id;
$scope.items = [$scope.itemsPlaceholder[id]];
}
}]);
app.directive('ngBindModel',function($compile){
return {
link: function(scope,element,attr){
element[0].removeAttribute('ng-bind-model');
element[0].setAttribute('ng-model',scope.$eval(attr.ngBindModel));
$compile(element[0])(scope);
}
};
});
app.directive('stringToNumber', function($compile) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
/*
ngModel.$parsers.push(function(value) {
return '' + value;
});
//*/
ngModel.$formatters.push(function(value) {
return parseFloat(value);
});
}
};
});
HTML:
<div ng-app="myApp" ng-controller="MyCtrl">
num1: {{calc.num1}} <br> num2: {{calc.num2}}
<br><BR>
{{labels.selected.options.id}}
<label>Select: </label>
<select ng-model="labels.selected" ng-options="options.name for options in labels.options track by options.id" ng-change="change();">
</select>
<BR><BR><BR>
<i> "normal" usage of ngModel -- </i>
<div ng-show="labels.selected.id == 0">
<label>{{items[0].label}} (model is: num1) </label><br>
<input type="number" name="inp{{$index}}" ng-model="calc.num1"/>
</div>
<div ng-show="labels.selected.id == 1">
<label>{{items[1].label}} (model is: num2) </label><br>
<input type="number" name="inp{{$index}}" ng-model="calc.num2"/>
</div>
<br> <i> string input for ngModel -- </i>
<div ng-repeat="item in items track by $index">
<label>{{item.label}} (model is: {{item.model}}) </label><br>
<input type="number" name="inp{{$index}}"
string-to-number ng-model="this[item.model]" ng-bind-model="item.model" />
</div>
</div>