哦,我的上帝!我做的!看看:)
當然,這個解決方案並不完美。它取決於控制器中使用的變量名稱。但它的作品!
jsfiddle上的示例。
<form name="ExampleForm" id="ExampleForm">
<div ng-repeat="item in items">
<div ng-if="item.fieldName!='subTotal1'">
<input ng-model="item.value">
<my-ng-model n-name="{{item.fieldName}}" n-value="item.value" obj="obj"></my-ng-model>
</div>
<div ng-if="item.fieldName=='subTotal1'">
{{item.expression }}={{$eval(item.expression)}}
</div>
</div>
{{obj|json}}
</form>
和JS控制器:
.controller('ExampleController', function($scope, $parse) {
$scope.obj = {};
$scope.items = [{
fieldName: "fname1",
value: 2
}, {
fieldName: "fname2",
value: 5
}, {
fieldName: "fname3",
value: 4
}, {
fieldName: "fname4",
value: 6
}, {
fieldName: "fname5",
value: 3
}, {
fieldName: "subTotal1",
expression: "obj.fname1 + obj.fname2 +obj.fname3 +obj.fname4 +obj.fname5"
}];})
和JS指令:
.directive('myNgModel', function() {
var root = {
restrict: "E",
replace: true,
scope: {
nName: "@",
nValue: "=",
obj: "="
},
template: '<div></div>',
link: function(scope) {
scope.obj[scope.nName] = scope.nValue*1;
scope.$watch('nValue', function(value) {
scope.obj[scope.nName] = value*1;
});
}
}
return root; })
修訂
現在它的工作原理沒有參照本地變量!
jsfiddle上的示例。
<form name="ExampleForm" id="ExampleForm">
<div ng-repeat="item in items">
<div ng-if="item.fieldName!='subTotal1'">
<input ng-model="item.value">
<my-ng-model n-name="{{item.fieldName}}" n-value="item.value" obj="obj"></my-ng-model>
</div>
</div>
<div ng-repeat="eval in evals">
{{eval.expression }}={{$eval(eval.expression,obj)}}
</div>
</form>
控制器
.controller('ExampleController', function($scope, $parse) {
$scope.obj = {};
$scope.items = [{
fieldName: "fname1",
value: 2
}, {
fieldName: "fname2",
value: 5
}, {
fieldName: "fname3",
value: 4
}, {
fieldName: "fname4",
value: 6
}, {
fieldName: "fname5",
value: 3
}, {
fieldName: "subTotal1",
expression: "fname1 + fname2 +fname3 +fname4 +fname5"
}];
$scope.evals = [];
angular.forEach($scope.items, function(item) {
if (item.expression) {
$scope.evals.push({
expression: item.expression
});
}
});})
和指導
.directive('myNgModel', function() {
var root = {
restrict: "E",
replace: true,
scope: {
nName: "@",
nValue: "=",
obj: "="
},
link: function(scope) {
scope.obj[scope.nName] = scope.nValue * 1;
scope.$watch('nValue', function(value) {
scope.obj[scope.nName] = value * 1;
});
}
}
return root;})
你可以修改你的服務。 ? –
我可以,如果我必須。你有什麼建議? – Chen